<?php


/**
 * 基金运行情况信息
 */
//传人基金id（基金基本信息表）
function yunxing_qingkuang_create($fund_id){
	  //我们为这个页面设置标题
	 drupal_set_title('新增基金运行情况信息');
	 $page_content = l('查看基金运行情况列表','yunxing_qingkuang/fundlist/'.$fund_id) . '<br />'. '<br />';
  $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$page_content .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
	 $render_array = array(
	   '#markup' => $page_content, 
	 );
	 
	 $form = drupal_get_form('yunxing_qingkuang_form',$fund_id);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function yunxing_qingkuang_form($form, &$form_state, $fund_id){
	 $form['bid'] = array('#type' => 'hidden', '#value' => $fund_id);
	 
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['year'] = array(
	  '#title' => t('年度(年)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['year'])?$_SESSION['yunxing_qingkuang_form']['year']:"",
	  '#description' => t('例如：2012'),
	 );
	 $form['all_money'] = array(
	  '#title' => t('总资产(万元)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['all_money'])?$_SESSION['yunxing_qingkuang_form']['all_money']:"",
	  '#description' => t('例如：250.55(下同)'),
	 ); 
	 $form['jing_money'] = array(
	  '#title' => t('净资产（万）'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['jing_money'])?$_SESSION['yunxing_qingkuang_form']['jing_money']:"",
	 );
	  $form['profit_money'] = array(
	  '#title' => t('利润(万元)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['profit_money'])?$_SESSION['yunxing_qingkuang_form']['profit_money']:"",
	 );
	 $form['input'] = array(
	  '#title' => t('收入(万元)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['input'])?$_SESSION['yunxing_qingkuang_form']['input']:"",
	 );

	$form['cost'] = array(
	  '#title' => t('成本费用(万元)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['cost'])?$_SESSION['yunxing_qingkuang_form']['cost']:"",
	 );
	 $form['invested'] = array(
	  '#title' => t('已投资(万元)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['invested'])?$_SESSION['yunxing_qingkuang_form']['invested']:"",
	 ); 
	 $form['current_deposit'] = array(
	  '#title' => t('活期存款(万元)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['current_deposit'])?$_SESSION['yunxing_qingkuang_form']['current_deposit']:"",
	 );
	  $form['fix_deposit'] = array(
	  '#title' => t('定期存款(万元)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['fix_deposit'])?$_SESSION['yunxing_qingkuang_form']['fix_deposit']:"",
	 );
	 $form['national_debt'] = array(
	  '#title' => t('国债(万元)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['national_debt'])?$_SESSION['yunxing_qingkuang_form']['national_debt']:"",
	 );
	  $form['other'] = array(
	  '#title' => t('其他(万元)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['other'])?$_SESSION['yunxing_qingkuang_form']['other']:"",
	 );
  	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['remark'])?$_SESSION['yunxing_qingkuang_form']['remark']:"",
	 );
	
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	  );
	  return $form;
}

function yunxing_qingkuang_form_validate($form, &$form_state){
	  if (drupal_strlen($form_state['values']['all_money']) > 15) {
	    form_set_error('all_money', '要求精度小于15 个字符');
	  } 
	  if (!($form_state['values']['all_money']>=0||$form_state['values']['all_money']<0)) {
	    form_set_error('all_money', '请输入数字');
	  }
	  
	   if (drupal_strlen($form_state['values']['jing_money']) > 15) {
	    form_set_error('jing_money', '要求精度小于15 个字符');
	  } 
	  if (!($form_state['values']['jing_money']>=0||$form_state['values']['jing_money']<0)) {
	    form_set_error('jing_money', '请输入数字');
	  }
	  
	   if (drupal_strlen($form_state['values']['profit_money']) > 15) {
	    form_set_error('profit_money', '要求精度小于15 个字符');
	  } 
	  if (!($form_state['values']['profit_money']>=0||$form_state['values']['profit_money']<0)) {
	    form_set_error('profit_money', '请输入数字');
	  }
	  
	   if (drupal_strlen($form_state['values']['input']) > 15) {
	    form_set_error('input', '要求精度小于15 个字符');
	  } 
	  if (!($form_state['values']['input']>=0||$form_state['values']['input']<0)) {
	    form_set_error('input', '请输入数字');
	  }
	  
	   if (drupal_strlen($form_state['values']['cost']) > 15) {
	    form_set_error('cost', '要求精度小于15 个字符');
	  } 
	  if (!($form_state['values']['cost']>=0||$form_state['values']['cost']<0)) {
	    form_set_error('cost', '请输入数字');
	  }
	  
	   if (drupal_strlen($form_state['values']['invested']) > 15) {
	    form_set_error('invested', '要求精度小于15 个字符');
	  } 
	  if (!($form_state['values']['invested']>=0||$form_state['values']['invested']<0)) {
	    form_set_error('invested', '请输入数字');
	  }
	  
	   if (drupal_strlen($form_state['values']['current_deposit']) > 15) {
	    form_set_error('current_deposit', '要求精度小于15 个字符');
	  } 
	  if (!($form_state['values']['current_deposit']>=0||$form_state['values']['current_deposit']<0)) {
	    form_set_error('current_deposit', '请输入数字');
	  }
	  
	   if (drupal_strlen($form_state['values']['fix_deposit']) > 15) {
	    form_set_error('fix_deposit', '要求精度小于15 个字符');
	  } 
	  if (!($form_state['values']['fix_deposit']>=0||$form_state['values']['fix_deposit']<0)) {
	    form_set_error('fix_deposit', '请输入数字');
	  }
	  
	   if (drupal_strlen($form_state['values']['national_debt']) > 15) {
	    form_set_error('national_debt', '要求精度小于15 个字符');
	  } 
	  if (!($form_state['values']['national_debt']>=0||$form_state['values']['national_debt']<0)) {
	    form_set_error('national_debt', '请输入数字');
	  }
	  
	   if (drupal_strlen($form_state['values']['other']) > 15) {
	    form_set_error('other', '要求精度小于15 个字符');
	  } 
	  if (!($form_state['values']['other']>=0||$form_state['values']['other']<0)) {
	    form_set_error('other', '请输入数字');
	  }
	  
}

function yunxing_qingkuang_form_submit($form, &$form_state){
	  //把表单的值存放在会话中去，由于这里涉及到了两个不同的表单之间传值。
	 $_SESSION['yunxing_qingkuang_form'] = $form_state['values'];
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'yunxing_qingkuang/confirm';
}
 
function yunxing_qingkuang_confirm_page(){
  //我们为这个页面设置标题
	 drupal_set_title('新增基金运行情况信息');
	 
	 //这里首先作了判断，如果会话中没有设置contactus_form，返回contactus
	 if(empty($_SESSION['yunxing_qingkuang_form'])){
	  drupal_goto('yunxing_qingkuang/fundlist');
	 }	
	 $render_array = array(
	   '#markup' => '', 
	 );
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('yunxing_qingkuang_confirm_form');
	 $render_array['#markup'] .= drupal_render($form);
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function yunxing_qingkuang_confirm_form(){
 
 $form['year'] = array(
  '#title' => t('年度(年)'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['yunxing_qingkuang_form']['year'])?$_SESSION['yunxing_qingkuang_form']['year']:"",
 );
 $form['all_money'] = array(
  '#title' => t('总资产(万元)'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['yunxing_qingkuang_form']['all_money'])?$_SESSION['yunxing_qingkuang_form']['all_money']:"",
 );
 $form['jing_money'] = array(
  '#title' => t('净资产（万）'),
   '#type' => 'item',
   '#markup' => isset($_SESSION['yunxing_qingkuang_form']['jing_money'])?$_SESSION['yunxing_qingkuang_form']['jing_money']:"",
 );
 $form['profit_money'] = array(
   '#title' => t('利润(万元)'),
   '#type' => 'item',
   '#markup' => isset($_SESSION['yunxing_qingkuang_form']['profit_money'])?$_SESSION['yunxing_qingkuang_form']['profit_money']:"",
 );
 $form['input'] = array(
  '#title' => t('收入(万元)'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['yunxing_qingkuang_form']['input'])?$_SESSION['yunxing_qingkuang_form']['input']:"",
 );
 $form['cost'] = array(
  '#title' => t('成本费用(万元)'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['yunxing_qingkuang_form']['cost'])?$_SESSION['yunxing_qingkuang_form']['cost']:"",
 );
 
 $form['invested'] = array(
  '#title' => t('已投资(万元)'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['yunxing_qingkuang_form']['invested'])?$_SESSION['yunxing_qingkuang_form']['invested']:"",
 );
 $form['current_deposit'] = array(
  '#title' => t('活期存款(万元)'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['yunxing_qingkuang_form']['current_deposit'])?$_SESSION['yunxing_qingkuang_form']['current_deposit']:"",
 );
 $form['fix_deposit'] = array(
   '#title' => t('定期存款(万元)'),
   '#type' => 'item',
   '#markup' => isset($_SESSION['yunxing_qingkuang_form']['fix_deposit'])?$_SESSION['yunxing_qingkuang_form']['fix_deposit']:"",
 );
 $form['national_debt'] = array(
   '#title' => t('国债(万元)'),
   '#type' => 'item',
   '#markup' => isset($_SESSION['yunxing_qingkuang_form']['national_debt'])?$_SESSION['yunxing_qingkuang_form']['national_debt']:"",
 );
 $form['other'] = array(
  '#title' => t('其他(万元)'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['yunxing_qingkuang_form']['other'])?$_SESSION['yunxing_qingkuang_form']['other']:"",
 );
 
 $form['remark'] = array(
  '#title' => t('备注'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['yunxing_qingkuang_form']['remark'])?$_SESSION['yunxing_qingkuang_form']['remark']:"",
 );

  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('返回'),
    '#submit' => array('yunxing_qingkuang_confirm_form_back'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('提交'),
  );
  
  return $form;
}

function yunxing_qingkuang_confirm_form_back($form, &$form_state){
 $form_state['redirect'] = 'yunxing_qingkuang/create/'.$_SESSION['yunxing_qingkuang_form']['bid'];
}

function yunxing_qingkuang_confirm_form_submit($form, &$form_state){
		/**
	   * 写入数据库
	   */
	   $values = NULL;
	  if(empty($_SESSION['yunxing_qingkuang_form'])){
		  drupal_goto('yunxing_qingkuang/create/'.$values['bid']);
	  }else{
		  $values = $_SESSION['yunxing_qingkuang_form'];
		  unset($_SESSION['yunxing_qingkuang_form']);
	  }
	  $last_id = db_insert('yunxing_qingkuang_info')
  		->fields(array(
  		     'fund_id' => $values['bid'],
   			 'year' => $values['year'],
   			 'all_money' => $values['all_money'],
   			 'jing_money' => $values['jing_money'],
   			 'profit_money' => $values['profit_money'],
   			 'input' => $values['input'],
   			 'cost' => $values['cost'],   			 
			 'invested' => $values['invested'],
   			 'current_deposit' => $values['current_deposit'],
   			 'fix_deposit' => $values['fix_deposit'],
   			 'national_debt' => $values['national_debt'],
   			 'other' => $values['other'],
   			 'remark' => $values['remark'],
  			))->execute();
	  if ($last_id!=NULL) {
	  	
		 $form_state['redirect'] = 'yunxing_qingkuang/list/'.$last_id;
	  } else {
	    
	    // 数据写入失败了
	    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
	    
	  }	
}

function yunxing_qingkuang_exportcsv_page($fund_id){
  $filename = '基金运行情况信息.csv' ;
  drupal_add_http_header('Content-Type', 'text/csv; charset=utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $filename . '"');
  $header = array(
       iconv('utf-8','gb2312','年度(年)'),
       iconv('utf-8','gb2312','总资产(万元)'),
       iconv('utf-8','gb2312', '净资产(万元)'),
       iconv('utf-8','gb2312', '利润(万元)'),
       iconv('utf-8','gb2312', '收入(万元)'),
       iconv('utf-8','gb2312', '成本费用(万元)'),
       iconv('utf-8','gb2312', '已投资(万元)'),
       iconv('utf-8','gb2312', '活期存款(万元)'),
       iconv('utf-8','gb2312', '定期存款(万元)'),
       iconv('utf-8','gb2312', '国债(万元)'),
       iconv('utf-8','gb2312', '其他(万元)'),
       iconv('utf-8','gb2312', '备注'),
      );
  print implode(',', $header) ."\r\n";
  $query = db_select('yunxing_qingkuang_info', 'n')
      ->fields ('n', array (
      'id',
      'year',
      'all_money',
      'jing_money',
      'profit_money',
      'input',
      'cost',
      'invested',
      'current_deposit',
      'fix_deposit',
      'national_debt',
      'other',
      'remark',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();
  foreach ($results as $node) {
      $datetime = str_replace(array(',',",",'，',"，") , " ", format_date($node->timestamp, 'custom', 'Y-m-d'));
      $values = array($node->year, $node->all_money, $node->jing_money, 
        $node->profit_money,$node->input,  $node->cost, $node->invested, $node->current_deposit, 
        $node->fix_deposit,$node->national_debt,  $node->other,  $node->remark); 
	  $str = implode(',', $values) ."\r\n";
	  $str = iconv('utf-8','gb2312',$str);
	  print $str;
    }

  
}

//传人基金id
function yunxing_qingkuang_fundlist_perpage($fund_id) {
  $html = l('返回基金列表','yunxing_qingkuang/fundlist') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';  
  //$html .= l('添加基金运行情况信息','yunxing_qingkuang/create/'.$fund_id) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .= l('导出','yunxing_qingkuang/exportcsv/'.$fund_id) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $options = array(
  'target_id' => 'printable_div',
  'value' => t('Print'),
  'type' => 'link',
  'custom_css' => drupal_get_path('module','my_module').'/css/print.css',
  );

  $html .= area_print_form($options). '<br />'. '<br />';
  $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
  $html .= '<div id="printable_div">';
  $header = array(
      array('data' => '年度(年)'),
      array('data' => '总资产(万元)'),
      array('data' => '已投资(万元)'),
      array('data' => '利润(万元)'),
      array('data' => '成本费用(万元)'),
      array('data' => '收入(万元)'),
      array('data' => '详情'),
      );
  $query = db_select('yunxing_qingkuang_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(20)//20 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'year',
      'all_money',
      'invested',
      'profit_money',
      'cost',
      'input',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        $node->year,
        $node->all_money,
        $node->invested,
        $node->profit_money,
        $node->cost,
        $node->input,
        l('查看详情', 'yunxing_qingkuang/list/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => l('填写基金运行情况信息','yunxing_qingkuang/create/'.$fund_id),//Optional empty text for the table if resultset is empty
      )
      );
  $html .= '</div>';
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  $html .= l('上传季度报告','yunxing_qingkuangfile/create_jidu/'.$fund_id).'<br>';
  $header = array(
      array('data' => '季度报告'),
      array('data' => '提交人'),
      array('data' => '上传时间'),
      array('data' => '备注'),
      );
  $query = db_select('yunxing_qingkuang_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=')
	  ->condition('type',1,'=')
	  ->condition('time_type',0,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'yunxing_qingkuangfile/list/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  
  $html .=  l('上传半年度报告','yunxing_qingkuangfile/create_jidu/'.$fund_id).'<br>'; 
  $header = array(
      array('data' => '半年度报告'),
      array('data' => '提交人'),
      array('data' => '上传时间'),
      array('data' => '备注'),
      );
  $query = db_select('yunxing_qingkuang_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=')
	  ->condition('type',1,'=')
	  ->condition('time_type',1,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'yunxing_qingkuangfile/list/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  
  $html .= l('上传年度报告','yunxing_qingkuangfile/create_jidu/'.$fund_id).'<br>';
  $header = array(
      array('data' => '年度报告'),
      array('data' => '提交人'),
      array('data' => '上传时间'),
      array('data' => '备注'),
      );
  $query = db_select('yunxing_qingkuang_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=')
	  ->condition('type',1,'=')
	  ->condition('time_type',2,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'yunxing_qingkuangfile/list/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );  
  return ($html); 
}
//传人基金运行情况id
function yunxing_qingkuang_per_page($perid) {
 
  // content variable that will be returned for display
  $page_content = '';
  $page_content .= l('返回基金列表','yunxing_qingkuang/fundlist') . '<br />'. '<br />';  
  drupal_set_title('管理该项基金运行情况信息');
	 
  $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
  $form = drupal_get_form('yunxing_qingkuang_edit_form',$perid);
  $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;
}

function yunxing_qingkuang_edit_form($form, &$form_state, $perid){
  $query = "SELECT * FROM " .
           "{yunxing_qingkuang_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $year = '';
  $all_money = '';
  $jing_money = '';
  $profit_money = '';
  $input = '';
  $cost = '';
  $invested = '';
  $input = '';
  $national_debt = '';
  $fix_deposit = '';
  $current_deposit = '';
  $other = '';
  $remark = '';

  foreach ($queryResult as $links ) {
	$year = $links->year;
    $all_money = $links->all_money;
    $jing_money = $links->jing_money;
    $profit_money = $links->profit_money;
    $input = $links->input;
    $cost = $links->cost;
	$invested = $links->invested;
    $input = $links->input;
    $national_debt = $links->national_debt;
    $fix_deposit = $links->fix_deposit ;
	$current_deposit = $links->current_deposit;
	$other = $links->other ;
    $remark = $links->remark;
  }
  // More coming....
  if ($queryResult == '') {
    $form = NULL;
  }
  else{
   $form['bid'] = array('#type' => 'hidden', '#value' => $perid);
    $form['year'] = array(
	  '#title' => t('年度(年)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['year'])?$_SESSION['yunxing_qingkuang_form']['year']:$year,
	  '#description' => t('例如：2012'),
	 );
	 $form['all_money'] = array(
	  '#title' => t('总资产(万元)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['all_money'])?$_SESSION['yunxing_qingkuang_form']['all_money']:$all_money,
	  '#description' => t('例如：250.55(下同)'),
	 ); 
	 $form['jing_money'] = array(
	  '#title' => t('净资产（万）'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['jing_money'])?$_SESSION['yunxing_qingkuang_form']['jing_money']:$jing_money,
	 );
	  $form['profit_money'] = array(
	  '#title' => t('利润(万元)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['profit_money'])?$_SESSION['yunxing_qingkuang_form']['profit_money']:$profit_money,
	 );
	 $form['input'] = array(
	  '#title' => t('收入(万元)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['input'])?$_SESSION['yunxing_qingkuang_form']['input']:$input,
	 );

	$form['cost'] = array(
	  '#title' => t('成本费用(万元)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['cost'])?$_SESSION['yunxing_qingkuang_form']['cost']:$cost,
	 );
	 $form['invested'] = array(
	  '#title' => t('已投资(万元)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['invested'])?$_SESSION['yunxing_qingkuang_form']['invested']:$invested,
	 ); 
	 $form['current_deposit'] = array(
	  '#title' => t('活期存款(万元)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['current_deposit'])?$_SESSION['yunxing_qingkuang_form']['current_deposit']:$current_deposit,
	 );
	  $form['fix_deposit'] = array(
	  '#title' => t('定期存款(万元)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['fix_deposit'])?$_SESSION['yunxing_qingkuang_form']['fix_deposit']:$fix_deposit,
	 );
	 $form['national_debt'] = array(
	  '#title' => t('国债(万元)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['national_debt'])?$_SESSION['yunxing_qingkuang_form']['national_debt']:$national_debt,
	 );
	  $form['other'] = array(
	  '#title' => t('其他(万元)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['other'])?$_SESSION['yunxing_qingkuang_form']['other']:$other,
	 );
  	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuang_form']['remark'])?$_SESSION['yunxing_qingkuang_form']['remark']:$remark,
	 );
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	  
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该基金运行情况信息'),
	    '#submit' => array('yunxing_qingkuang_edit_form_deleate'),
	  );
  	
  }
  
  return $form;
}

function yunxing_qingkuang_edit_form_submit($form, &$form_state){
	  $values = NULL;
	  $values = $form_state['values'];
       db_update('yunxing_qingkuang_info')
  		->fields(array(
		 	'year' => $values['year'],
   			 'all_money' => $values['all_money'],
   			 'jing_money' => $values['jing_money'],
   			 'profit_money' => $values['profit_money'],
   			 'input' => $values['input'],
   			 'cost' => $values['cost'],   			 
			 'invested' => $values['invested'],
   			 'current_deposit' => $values['current_deposit'],
   			 'fix_deposit' => $values['fix_deposit'],
   			 'national_debt' => $values['national_debt'],
   			 'other' => $values['other'],
   			 'remark' => $values['remark'],
  			))
  		->condition('id', $values['bid'])
  		->execute();
	 $form_state['redirect'] = 'yunxing_qingkuang/list/'.$values['bid'];
}

function yunxing_qingkuang_edit_form_deleate($form, &$form_state){
	 $values = NULL;
	 $_SESSION['yunxing_qingkuang_edit_form'] = $form_state['values'];
	 $values = $_SESSION['yunxing_qingkuang_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'yunxing_qingkuang/deleate/'.$values['bid'];
}

function yunxing_qingkuang_deleate_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该基金运行情况信息将不可恢复！';
  
  drupal_set_title('删除该基金运行情况信息');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('yunxing_qingkuang_deleate_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function yunxing_qingkuang_deleate_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('yunxing_qingkuang_deleate_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function yunxing_qingkuang_deleate_form_back($form, &$form_state){
	if(empty($_SESSION['yunxing_qingkuang_edit_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'yunxing_qingkuang/fundlist';
	  }else{
		  $values = $_SESSION['yunxing_qingkuang_edit_form'];
		  unset($_SESSION['yunxing_qingkuang_edit_form']);
		  $form_state['redirect'] = 'yunxing_qingkuang/list/'.$values['bid'];
	  }
}

function yunxing_qingkuang_deleate_form_submit($form, &$form_state){
  //简单的重定向到contactus页面
 if(empty($_SESSION['yunxing_qingkuang_edit_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'yunxing_qingkuang/fundlist';
	  }else{
		  $values = $_SESSION['yunxing_qingkuang_edit_form'];
		  unset($_SESSION['yunxing_qingkuang_edit_form']);
		  db_delete('yunxing_qingkuang_info')
			->condition('id' ,$values['bid'])
			->execute();
		  $form_state['redirect'] = 'yunxing_qingkuang/fundlist';;
	  }

}

//基金运行情况设置基金选择入口
function yunxing_qingkuang_fundlist_page() {
 $html = '';
 if(!user_access( 'upload fund template file')){
 		global $user;
		$query = "SELECT fund_id FROM {fund_basic_information} WHERE user_id = ?";
		$query_result = db_query($query,array($user->uid));
		$result_values = '';
		$fund_id = "";
		foreach ($query_result as $result_values ) {
			$fund_id = $result_values->fund_id;
		}
		 $header = array(
      array('data' => '基金名称', 'field' => 'registered_name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'contact'),
      array('data' => '基金运行情况基本信息管理', 'field' => 'info_set'),
      array('data' => '基金运行情况报告管理', 'field' => 'file_set'),
      array('data' => '基金不良信息记录管理', 'field' => 'file_set'),
      
      );
  $query = db_select('fund_basic_information', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'registered_name',
      'contact',
      ))
      ->condition('id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
		  $rows[] = array(
	      'data' => array(
	        $node->registered_name,
	        $node->contact,
	        l('基本信息管理', 'yunxing_qingkuang/fundlist/'.$node->id),
	        l('报告管理', 'yunxing_qingkuangfile/guidingfund/'.$node->id),
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
 }
 $header = array(
      array('data' => '基金名称', 'field' => 'registered_name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '基金运行情况基本信息管理', 'field' => 'info_set'),
      array('data' => '基金运行情况报告管理', 'field' => 'file_set'),      
      );
  $query = db_select('fund_basic_information', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'registered_name',
      'contact',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
		  $rows[] = array(
	      'data' => array(
	        $node->registered_name,
	        $node->contact,
	        l('基本信息管理', 'yunxing_qingkuang/fundlist/'.$node->id),
	        l('报告管理', 'yunxing_qingkuangfile/guidingfund/'.$node->id),
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

/////////
//基金运行报告管理
////////
//传入fund_id
function yunxing_qingkuangfile_create_jidu_page($perid){
	 drupal_set_title('基金运行季度报告提交');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('yunxing_qingkuangfile_create_jidu_form',$perid);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function yunxing_qingkuangfile_create_jidu_form($form, &$form_state, $perid){
	 $form['bid'] = array('#type' => 'hidden', '#value' => $perid);	 
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '基金运行季度报告',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx'),
		'file_validate_size' => array(20*1024*1024)),
	);
	//if(!user_access('upload fund template file')){
		
	$form['upload_name'] = array(
	  '#title' => t('提交人：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	//}
	
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function yunxing_qingkuangfile_create_jidu_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
			//$type = 1;
			$query = "SELECT id, name FROM " .
		           "{guiding_fund_info} where id = ? ";
		    $queryResult = db_query($query, array($values['bid'] ));
			$fundname = '';
			
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$fundname = $links->name;
				}
			}
			$upload_name = '';
			$filename .= $fundname."_基金运行季度报告";
			$upload_name = $values['upload_name'];
			/*$query = "SELECT id,file_managed_id FROM " .
		           "{yunxing_qingkuang_file_info} where fund_id = ? and time_type =? and type = ?";
		    $file_managed_id = '';  //已上传基金运行报告在file_managed表中对应的id
		    $queryResult = db_query($query, array($values['bid'],0,1));
			$uploadid = 0; //已上传基金运行报告id
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$file_managed_id = $links->file_managed_id;
					$uploadid = $links->id;
				}
			}
			if($uploadid==0){*/
				$last_id = db_insert('yunxing_qingkuang_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $upload_name,
			   			 'remark' => $values['remark'],
			   			 'fund_id' => $values['bid'],
			   			 'user_id' => $user->uid,
			   			 'type' => 1,
			   			 'time_type' => 0,
			   			 'file_managed_id' => $fid,
			  			))->execute();
				  if ($last_id!=NULL) {
				     
					 $form_state['redirect'] = 'yunxing_qingkuangfile/guidingfund/'.$values['bid'];
					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
			/*}
			else{
				if($file_managed_id>0){
					$file = file_load($file_managed_id);
				  if($file!=NULL){
					 file_delete($file);
				  }
					db_delete('file_managed')
				    ->condition('fid',$file_managed_id)
					->execute();
				}	
				db_update('yunxing_qingkuang_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'remark' => $values['remark'],
			   			 'fund_id' => $values['bid'],
			   			 'file_managed_id' => $fid,
			  			))
			  		->condition('id',$uploadid)
			  		->execute();
				$form_state['redirect'] = 'yunxing_qingkuangfile/guidingfund/'.$values['bid'];
			}
			*/
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function yunxing_qingkuangfile_create_jidu_template_page($perid){
	 drupal_set_title('基金运行季度报告模板上传');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('yunxing_qingkuangfile_create_jidu_template_form',$perid);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function yunxing_qingkuangfile_create_jidu_template_form($form, &$form_state, $perid){
	 $form['bid'] = array('#type' => 'hidden', '#value' => $perid);	 
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '基金运行季度报告模板',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx'),
		'file_validate_size' => array(20*1024*1024)),
	);
	//if(!user_access('upload fund template file')){
		
	$form['upload_name'] = array(
	  '#title' => t('提交人：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	//}
	
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function yunxing_qingkuangfile_create_jidu_template_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
			//$type = 1;
			$query = "SELECT id, name FROM " .
		           "{guiding_fund_info} where id = ? ";
		    $queryResult = db_query($query, array($values['bid'] ));
			$fundname = '';
			
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$fundname = $links->name;
				}
			}
			$upload_name = '';
			$filename .= $fundname."_基金运行季度报告模板";
			$upload_name = $values['upload_name'];

			/*$query = "SELECT id,file_managed_id FROM " .
		           "{yunxing_qingkuang_file_info} where fund_id = ? and time_type =? and type = ?";
		    $file_managed_id = '';  //已上传基金运行报告在file_managed表中对应的id
		    $queryResult = db_query($query, array($values['bid'],0,0 ));
			$uploadid = 0; //已上传基金运行报告id
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$file_managed_id = $links->file_managed_id;
					$uploadid = $links->id;
				}
			}
			if($uploadid==0){*/
				$last_id = db_insert('yunxing_qingkuang_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $upload_name,
			   			 'remark' => $values['remark'],
			   			 'fund_id' => $values['bid'],
			   			 'user_id' => $user->uid,
			   			 'type' => 0,
			   			 'time_type' => 0,
			   			 'file_managed_id' => $fid,
			  			))->execute();
				  if ($last_id!=NULL) {
					 $form_state['redirect'] = 'yunxing_qingkuangfile/guidingfund/'.$values['bid'];
					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
			/*}
			else{
				if($file_managed_id>0){
					$file = file_load($file_managed_id);
				  if($file!=NULL){
					 file_delete($file);
				  }
					db_delete('file_managed')
				    ->condition('fid',$file_managed_id)
					->execute();
				}	
				db_update('yunxing_qingkuang_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'remark' => $values['remark'],
			   			 'fund_id' => $values['bid'],
			   			 'file_managed_id' => $fid,
			  			))
			  		->condition('id',$uploadid)
			  		->execute();
				$form_state['redirect'] = 'yunxing_qingkuangfile/guidingfund/'.$values['bid'];
			}
			*/
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}


function yunxing_qingkuangfile_create_bannian_page($perid){
	 drupal_set_title('基金运行半年度报告提交');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('yunxing_qingkuangfile_create_bannian_form',$perid);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function yunxing_qingkuangfile_create_bannian_form($form, &$form_state, $perid){
	 $form['bid'] = array('#type' => 'hidden', '#value' => $perid);	 
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '基金运行半年度报告',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx'),
		'file_validate_size' => array(20*1024*1024)),
	);
	//if(!user_access('upload fund template file')){
		
	$form['upload_name'] = array(
	  '#title' => t('提交人：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	//}
	
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function yunxing_qingkuangfile_create_bannian_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
			//$type = 1;
			$query = "SELECT id, name FROM " .
		           "{guiding_fund_info} where id = ? ";
		    $queryResult = db_query($query, array($values['bid'] ));
			$fundname = '';
			
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$fundname = $links->name;
				}
			}
			$upload_name = '';
			$filename .= $fundname."_基金运行半年度报告";
			$upload_name = $values['upload_name'];
			
			/*$query = "SELECT id,file_managed_id FROM " .
		           "{yunxing_qingkuang_file_info} where fund_id = ? and time_type =? and type = ?";
		    $file_managed_id = '';  //已上传基金运行报告在file_managed表中对应的id
		    $queryResult = db_query($query, array($values['bid'],1,1 ));
			$uploadid = 0; //已上传基金运行报告id
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$file_managed_id = $links->file_managed_id;
					$uploadid = $links->id;
				}
			}
			if($uploadid==0){*/
				$last_id = db_insert('yunxing_qingkuang_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $upload_name,
			   			 'remark' => $values['remark'],
			   			 'fund_id' => $values['bid'],
			   			 'user_id' => $user->uid,
			   			 'type' => 1,
			   			 'time_type' => 1,
			   			 'file_managed_id' => $fid,
			  			))->execute();
				  if ($last_id!=NULL) {
					 $form_state['redirect'] = 'yunxing_qingkuangfile/guidingfund/'.$values['bid'];
					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
			/*}
			else{
				if($file_managed_id>0){
					$file = file_load($file_managed_id);
				  if($file!=NULL){
					 file_delete($file);
				  }
					db_delete('file_managed')
				    ->condition('fid',$file_managed_id)
					->execute();
				}	
				db_update('yunxing_qingkuang_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'remark' => $values['remark'],
			   			 'fund_id' => $values['bid'],
			   			 'file_managed_id' => $fid,
			  			))
			  		->condition('id',$uploadid)
			  		->execute();
				$form_state['redirect'] = 'yunxing_qingkuangfile/guidingfund/'.$values['bid'];
			}*/
			
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function yunxing_qingkuangfile_create_bannian_template_page($perid){
	 drupal_set_title('基金运行半年度报告提交');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('yunxing_qingkuangfile_create_bannian_template_form',$perid);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function yunxing_qingkuangfile_create_bannian_template_form($form, &$form_state, $perid){
	 $form['bid'] = array('#type' => 'hidden', '#value' => $perid);	 
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '基金运行半年度报告',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx'),
		'file_validate_size' => array(20*1024*1024)),
	);
	//if(!user_access('upload fund template file')){
		
	$form['upload_name'] = array(
	  '#title' => t('提交人：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	//}
	
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function yunxing_qingkuangfile_create_bannian_template_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
			//$type = 1;
			$query = "SELECT id, name FROM " .
		           "{guiding_fund_info} where id = ? ";
		    $queryResult = db_query($query, array($values['bid'] ));
			$fundname = '';
			
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$fundname = $links->name;
				}
			}
			$upload_name = '';

			$filename .= $fundname."_基金运行半年度报告模板";
			$upload_name = $values['upload_name'];

			/*$query = "SELECT id,file_managed_id FROM " .
		           "{yunxing_qingkuang_file_info} where fund_id = ? and time_type =? and type = ?";
		    $file_managed_id = '';  //已上传基金运行报告在file_managed表中对应的id
		    $queryResult = db_query($query, array($values['bid'],1,0 ));
			$uploadid = 0; //已上传基金运行报告id
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$file_managed_id = $links->file_managed_id;
					$uploadid = $links->id;
				}
			}
			if($uploadid==0){*/
				$last_id = db_insert('yunxing_qingkuang_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $upload_name,
			   			 'remark' => $values['remark'],
			   			 'fund_id' => $values['bid'],
			   			 'user_id' => $user->uid,
			   			 'type' => 0,
			   			 'time_type' => 1,
			   			 'file_managed_id' => $fid,
			  			))->execute();
				  if ($last_id!=NULL) {
				   
					 $form_state['redirect'] = 'yunxing_qingkuangfile/guidingfund/'.$values['bid'];
					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
			/*}
			else{
				if($file_managed_id>0){
					$file = file_load($file_managed_id);
				  if($file!=NULL){
					 file_delete($file);
				  }
					db_delete('file_managed')
				    ->condition('fid',$file_managed_id)
					->execute();
				}	
				db_update('yunxing_qingkuang_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'remark' => $values['remark'],
			   			 'fund_id' => $values['bid'],
			   			 'file_managed_id' => $fid,
			  			))
			  		->condition('id',$uploadid)
			  		->execute();
				
				$form_state['redirect'] = 'yunxing_qingkuangfile/guidingfund/'.$values['bid'];
			}
			*/
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}


function yunxing_qingkuangfile_create_niandu_page($perid){
	 drupal_set_title('基金运行年度报告提交');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('yunxing_qingkuangfile_create_niandu_form',$perid);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function yunxing_qingkuangfile_create_niandu_form($form, &$form_state, $perid){
	 $form['bid'] = array('#type' => 'hidden', '#value' => $perid);	 
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '基金运行年度报告',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx'),
		'file_validate_size' => array(20*1024*1024)),
	);
	//if(!user_access('upload fund template file')){
		
	$form['upload_name'] = array(
	  '#title' => t('提交人：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	//}
	
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function yunxing_qingkuangfile_create_niandu_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
			//$type = 1;
			$query = "SELECT id, name FROM " .
		           "{guiding_fund_info} where id = ? ";
		    $queryResult = db_query($query, array($values['bid'] ));
			$fundname = '';
			
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$fundname = $links->name;
				}
			}
			$upload_name = '';
			$filename .= $fundname."_基金运行年度报告";
			$upload_name = $values['upload_name'];

			/*$query = "SELECT id,file_managed_id FROM " .
		           "{yunxing_qingkuang_file_info} where fund_id = ? and time_type =? and type = ?";
		    $file_managed_id = '';  //已上传基金运行报告在file_managed表中对应的id
		    $queryResult = db_query($query, array($values['bid'],2,1 ));
			$uploadid = 0; //已上传基金运行报告id
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$file_managed_id = $links->file_managed_id;
					$uploadid = $links->id;
				}
			}
			if($uploadid==0){*/
				$last_id = db_insert('yunxing_qingkuang_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $upload_name,
			   			 'remark' => $values['remark'],
			   			 'fund_id' => $values['bid'],
			   			 'user_id' => $user->uid,
			   			 'type' => 1,
			   			 'time_type' => 2,
			   			 'file_managed_id' => $fid,
			  			))->execute();
				  if ($last_id!=NULL) {
				    
					 $form_state['redirect'] = 'yunxing_qingkuangfile/guidingfund/'.$values['bid'];
					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
			/*}
			else{
				if($file_managed_id>0){
					$file = file_load($file_managed_id);
				  if($file!=NULL){
					 file_delete($file);
				  }
					db_delete('file_managed')
				    ->condition('fid',$file_managed_id)
					->execute();
				}	
				db_update('yunxing_qingkuang_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'remark' => $values['remark'],
			   			 'fund_id' => $values['bid'],
			   			 'file_managed_id' => $fid,
			  			))
			  		->condition('id',$uploadid)
			  		->execute();
				
				$form_state['redirect'] = 'yunxing_qingkuangfile/guidingfund/'.$values['bid'];
			}*/
			
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function yunxing_qingkuangfile_create_niandu_template_page($perid){
	 drupal_set_title('基金运行年度报告提交');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('yunxing_qingkuangfile_create_niandu_template_form',$perid);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function yunxing_qingkuangfile_create_niandu_template_form($form, &$form_state, $perid){
	 $form['bid'] = array('#type' => 'hidden', '#value' => $perid);	 
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '基金运行年度报告',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx'),
		'file_validate_size' => array(20*1024*1024)),
	);
	//if(!user_access('upload fund template file')){
		
	$form['upload_name'] = array(
	  '#title' => t('提交人：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	//}
	
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function yunxing_qingkuangfile_create_niandu_template_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
			//$type = 1;
			$query = "SELECT id, name FROM " .
		           "{guiding_fund_info} where id = ? ";
		    $queryResult = db_query($query, array($values['bid'] ));
			$fundname = '';
			
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$fundname = $links->name;
				}
			}
			$upload_name = '';
			$filename .= $fundname."_基金运行年度报告";
			$upload_name = $values['upload_name'];
		
			/*$query = "SELECT id,file_managed_id FROM " .
		           "{yunxing_qingkuang_file_info} where fund_id = ? and time_type =? and type = ?";
		    $file_managed_id = '';  //已上传基金运行报告在file_managed表中对应的id
		    $queryResult = db_query($query, array($values['bid'],2,0 ));
			$uploadid = 0; //已上传基金运行报告id
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$file_managed_id = $links->file_managed_id;
					$uploadid = $links->id;
				}
			}
			if($uploadid==0){*/
				$last_id = db_insert('yunxing_qingkuang_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $upload_name,
			   			 'remark' => $values['remark'],
			   			 'fund_id' => $values['bid'],
			   			 'user_id' => $user->uid,
			   			 'type' => 0,
			   			 'time_type' => 2,
			   			 'file_managed_id' => $fid,
			  			))->execute();
				  if ($last_id!=NULL) {
				     
					 $form_state['redirect'] = 'yunxing_qingkuangfile/guidingfund/'.$values['bid'];
					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
			/*}
			else{
				if($file_managed_id>0){
					$file = file_load($file_managed_id);
				  if($file!=NULL){
					 file_delete($file);
				  }
					db_delete('file_managed')
				    ->condition('fid',$file_managed_id)
					->execute();
				}	
				db_update('yunxing_qingkuang_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'remark' => $values['remark'],
			   			 'fund_id' => $values['bid'],
			   			 'file_managed_id' => $fid,
			  			))
			  		->condition('id',$uploadid)
			  		->execute();
				
				$form_state['redirect'] = 'yunxing_qingkuangfile/guidingfund/'.$values['bid'];
			}
			*/
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}


function yunxing_qingkuangfile_list_perpage($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;
  $query = "SELECT id, name,url,timestamp,remark, fund_id,user_id,type,upload_name FROM " .
           "{yunxing_qingkuang_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  foreach ($queryResult as $links ) {

   $page_content .= l('返回基金列表','yunxing_qingkuangfile/guidingfund/'.$links->fund_id) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
   //$page_content .= l('切换成编辑模式','yunxing_qingkuangfile/edit/'.$perid)  . '<br />'. '<br />';
   if($links->type != 1 && user_access('upload fund template file')){
 		$page_content .= l('切换成编辑模式','yunxing_qingkuangfile/edit/'.$perid)  . '<br />'. '<br />'; 
   }
   else if($links->type == 1 && user_access('upload fund result file'))
   {
  	 	$page_content .= l('切换成编辑模式','yunxing_qingkuangfile/edit/'.$perid)  . '<br />'. '<br />'; 
   }
   else{
   	    $page_content .= '<br />'. '<br />';
   }
   
	if($links->type == 0) {
    	$page_content .= '<h5>基金运行报告模板下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/drupal/sites/default/files/'.$links->url).'<br />'.'<br />';
		$page_content .= '<h5>上传时间:</h5>'. format_date($links->timestamp, 'custom', 'Y-m-d').'<br />'.'<br />';
    	$page_content .= '<h5>备注: </h5>'.$links->remark.'<br />'.'<br />';
    }	
	else if($links->type == 1) {
  		//$page_content .= l('申报企业信息','enterprise_information/view/'.$info_id) . '<br />'. '<br />';
		$page_content .= '<h5>基金运行报告下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/drupal/sites/default/files/'.$links->url).'<br />'.'<br />';
		$page_content .= '<h5>提交人:</h5>'.$links->upload_name.'<br />'.'<br />';
		$page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'Y-m-d').'<br />'.'<br />';
    	$page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';	
    }
  }
  // More coming....
  if ($page_content == '') {
    $page_content = "没有该上传基金运行报告信息.";
  }

  return $page_content;
}

//传入fund_id
function yunxing_qingkuangfile_guidingfund_page($fund_id) {
  // content variable that will be returned for display
  $html = '';
  $html .= l('返回基金列表','yunxing_qingkuang/fundlist') . '<br />'. '<br />';
  $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
  if(user_access('upload fund template file')){
  	  $html .=  l('上传季度报告模板','yunxing_qingkuangfile/create_jidu_template/'.$fund_id). '<br />';
  }
  $header = array(
      array('data' => '季度报告模板'),
      array('data' => '提交人'),
      array('data' => '上传时间'),
      array('data' => '备注'),
      );
  $query = db_select('yunxing_qingkuang_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=')
	  ->condition('type',0,'=')
	  ->condition('time_type',0,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'yunxing_qingkuangfile/list/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  
  $html .= l('上传季度报告','yunxing_qingkuangfile/create_jidu/'.$fund_id).'<br>';
  $header = array(
      array('data' => '季度报告'),
      array('data' => '提交人'),
      array('data' => '上传时间'),
      array('data' => '备注'),
      );
  $query = db_select('yunxing_qingkuang_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=')
	  ->condition('type',1,'=')
	  ->condition('time_type',0,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'yunxing_qingkuangfile/list/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  if(user_access('upload fund template file')){
  	$html .=   l('上传半年度报告模板','yunxing_qingkuangfile/create_bannian_template/'.$fund_id).'<br>';
  }
  $header = array(
      array('data' => '半年度报告模板'),
      array('data' => '提交人'),
      array('data' => '上传时间'),
      array('data' => '备注'),
      );
  $query = db_select('yunxing_qingkuang_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=')
	  ->condition('type',0,'=')
	  ->condition('time_type',1,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'yunxing_qingkuangfile/list/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' =>'没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  
  $html .= l('上传半年度报告','yunxing_qingkuangfile/create_bannian/'.$fund_id).'<br>';   
  $header = array(
      array('data' => '半年度报告'),
      array('data' => '提交人'),
      array('data' => '上传时间'),
      array('data' => '备注'),
      );
  $query = db_select('yunxing_qingkuang_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=')
	  ->condition('type',1,'=')
	  ->condition('time_type',1,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'yunxing_qingkuangfile/list/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  if(user_access('upload fund template file')){
  	$html .= l('上传年度报告模板','yunxing_qingkuangfile/create_niandu_template/'.$fund_id).'<br>';
  }
  $header = array(
      array('data' => '年度报告模板'),
      array('data' => '提交人'),
      array('data' => '上传时间'),
      array('data' => '备注'),
      );
  $query = db_select('yunxing_qingkuang_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=')
	  ->condition('type',0,'=')
	  ->condition('time_type',2,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'yunxing_qingkuangfile/list/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  
  $html .= l('上传年度报告','yunxing_qingkuangfile/create_niandu/'.$fund_id).'<br>';
  $header = array(
      array('data' => '年度报告'),
      array('data' => '提交人'),
      array('data' => '上传时间'),
      array('data' => '备注'),
      );
  $query = db_select('yunxing_qingkuang_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=')
	  ->condition('type',1,'=')
	  ->condition('time_type',2,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'yunxing_qingkuangfile/list/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function yunxing_qingkuangfile_edit_perpage($perid) {
  $page_content = '';
  //$page_content .= l('查看基金信息','guidingfund/list/') . '<br />'. '<br />';
  $page_content .= l('切换成浏览模式','yunxing_qingkuangfile/list/'.$perid) . '<br />'. '<br />'; 	
  drupal_set_title('基金运行报告管理');
	 
  $query = "SELECT id,name, url FROM " .
           "{yunxing_qingkuang_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
		  $ifempty = FALSE;
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('yunxing_qingkuangfile_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{
	 	 $page_content .= '<h5>已提交基金运行报告:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/drupal/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('yunxing_qingkuangfile_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function yunxing_qingkuangfile_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark, fund_id,user_id,type,upload_name,file_managed_id FROM " .
           "{yunxing_qingkuang_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $reply_remark = '';
  $fund_id = '';
  $type = '';
  $upload_name = '';
  global $user;
 foreach ($queryResult as $links ) {
  	/*if($links->user_id != $user->uid){
  		if(!user_access('upload fund template file')){
  			$query = "SELECT id, name,url,remark, fund_id,user_id,type,upload_name,file_managed_id FROM " .
           		"{yunxing_qingkuang_file_info} where user_id = ?";
			$queryResult = db_query($query, array($user->uid));
			foreach ($queryResult as $insidelinks ) {
				$links = $insidelinks;
			}
  		}
  	}*/
	$name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
	$fund_id =  $links->fund_id;
	$type =  $links->type;
  	$upload_name = $links->upload_name;
	$file_managed_id = $links->file_managed_id;
  }
   if($type == 1){
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
   	$form['type'] = array('#type' => 'hidden', '#value' => $type);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
	$form['fund_id'] = array('#type' => 'hidden', '#value' => $fund_id);
	
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuangfile_edit_form']['name'])?$_SESSION['yunxing_qingkuangfile_edit_form']['name']:$name,
	 );
	 
    $form['upload_name'] = array(
	  '#title' => t('提交人'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuangfile_edit_form']['upload_name'])?$_SESSION['yunxing_qingkuangfile_edit_form']['upload_name']:$upload_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交基金运行报告',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['yunxing_qingkuangfile_edit_form']['remark'])?$_SESSION['yunxing_qingkuangfile_edit_form']['remark']:$remark,
	 );
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该报告'),
	    '#submit' => array('yunxing_qingkuangfile_edit_form_deleate'),
	  );
   }	
	else if($type == 0){
	   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	   	$form['type'] = array('#type' => 'hidden', '#value' => $type);
		$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
		$form['fund_id'] = array('#type' => 'hidden', '#value' => $fund_id);
		
		$form['name'] = array(
		  '#title' => t('文件名'),
		  '#type' => 'textfield',
		  '#required' => TRUE,
		  '#default_value' =>isset($_SESSION['yunxing_qingkuangfile_edit_form']['name'])?$_SESSION['yunxing_qingkuangfile_edit_form']['name']:$name,
		 );
		  $form['upload_name'] = array(
		  '#title' => t('提交人'),
		  '#type' => 'textfield',
		  '#required' => TRUE,
		  '#default_value' =>isset($_SESSION['yunxing_qingkuangfile_edit_form']['upload_name'])?$_SESSION['yunxing_qingkuangfile_edit_form']['upload_name']:$upload_name,
		 );
		 
		 $form['upload'] = array(
		  '#type' => 'managed_file',
		  '#title' => '重新提交基金运行报告模板',
		  '#required' => FAlSE,
		  '#upload_location' => 'public://my_uploads',
		  '#upload_validators' => array(
		    'file_validate_extensions' => array('doc xls pdf docx xlsx'),
			'file_validate_size' => array(20*1024*1024)),
		);
		
		 $form['remark'] = array(
		  '#title' => t('备注'),
		  '#type' => 'textarea',
		  '#required' => FALSE,
		  '#default_value' =>isset($_SESSION['yunxing_qingkuangfile_edit_form']['remark'])?$_SESSION['yunxing_qingkuangfile_edit_form']['remark']:$remark,
		 );
		 
		 $form['submit'] = array(
		    '#type' => 'submit',
		    '#value' => t('提交修改'),
		  );
		 //表单元素“提交”按钮
		  $form['deleate'] = array(
		    '#type' => 'submit',
		    '#value' => t('删除该模板'),
		    '#submit' => array('yunxing_qingkuangfile_edit_form_deleate'),
		  );
   	  }
	  
  return $form;
}

function yunxing_qingkuangfile_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	
	global $user; 
	$filetype = $values['type'];
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			if($filetype == 1){
				db_update('yunxing_qingkuang_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'file_managed_id' => $fid,
			   	    'upload_name' => $values['upload_name'],
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
			}
			else  if($filetype == 0){
				db_update('yunxing_qingkuang_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'file_managed_id' => $fid,
			   	    'upload_name' => $values['upload_name'],
			  		))
			  		->condition('id',$uploadid)
			  		->execute();			
			}			
			$form_state['redirect'] = 'yunxing_qingkuangfile/list/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
			if($filetype == 1){
				db_update('yunxing_qingkuang_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'upload_name' => $values['upload_name'],
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
			}
			else  if($filetype == 0){
				db_update('yunxing_qingkuang_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'upload_name' => $values['upload_name'],
			  		))
			  		->condition('id',$uploadid)
			  		->execute();			
			}			
			$form_state['redirect'] = 'yunxing_qingkuangfile/list/'.$values['bid'];
	}
}

function yunxing_qingkuangfile_edit_form_deleate($form, &$form_state){
	 $values = NULL;
	 $_SESSION['yunxing_qingkuangfile_edit_form'] = $form_state['values'];
	 $values = $_SESSION['yunxing_qingkuangfile_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'yunxing_qingkuangfile/deleate/'.$values['bid'];
}

function yunxing_qingkuangfile_deleate_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后申报内容将不可恢复！';
  
  drupal_set_title('删除申报内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('yunxing_qingkuangfile_deleate_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function yunxing_qingkuangfile_deleate_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('yunxing_qingkuangfile_deleate_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function yunxing_qingkuangfile_deleate_form_back($form, &$form_state){
	if(empty($_SESSION['yunxing_qingkuangfile_edit_form'])){
		  	$form_state['redirect'] = 'yunxing_qingkuangfile/list';
	  }else{
		  $values = $_SESSION['yunxing_qingkuangfile_edit_form'];
		  unset($_SESSION['yunxing_qingkuangfile_edit_form']);
		  $form_state['redirect'] = 'yunxing_qingkuangfile/edit/'.$values['bid'];
	  }
}

function yunxing_qingkuangfile_deleate_form_submit($form, &$form_state){
 if(empty($_SESSION['yunxing_qingkuangfile_edit_form'])){
		  	$form_state['redirect'] = 'yunxing_qingkuang/fundlist';
	  }else{
		  $values = $_SESSION['yunxing_qingkuangfile_edit_form'];
		  unset($_SESSION['yunxing_qingkuangfile_edit_form']);
		  
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('yunxing_qingkuang_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'yunxing_qingkuang/fundlist';

	  }

}

///////////
//托管银行资料管理
///////////
function custodian_bank_create_jidu_page($perid){
	 drupal_set_title('托管银行季度报告提交');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('custodian_bank_create_jidu_form',$perid);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function custodian_bank_create_jidu_form($form, &$form_state, $perid){
	 $form['bid'] = array('#type' => 'hidden', '#value' => $perid);	 
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '托管银行季度报告',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx'),
		'file_validate_size' => array(20*1024*1024)),
	);
	//if(!user_access('upload fund template file')){
		
	$form['upload_name'] = array(
	  '#title' => t('提交人：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	//}
	
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function custodian_bank_create_jidu_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
			//$type = 1;
			$query = "SELECT id, name FROM " .
		           "{guiding_fund_info} where id = ? ";
		    $queryResult = db_query($query, array($values['bid'] ));
			$fundname = '';
			
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$fundname = $links->name;
				}
			}
			$upload_name = '';
			$filename .= $fundname."_托管银行季度报告";
			$upload_name = $values['upload_name'];
			$query = "SELECT id,file_managed_id FROM " .
		           "{custodian_bank_file_info} where fund_id = ? and time_type =? ";
		    $file_managed_id = '';  //已上传托管银行报告在file_managed表中对应的id
		    $queryResult = db_query($query, array($values['bid'],0));
			/*$uploadid = 0; //已上传托管银行报告id
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$file_managed_id = $links->file_managed_id;
					$uploadid = $links->id;
				}
			}*/
			//if($uploadid==0){
				$last_id = db_insert('custodian_bank_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $upload_name,
			   			 'remark' => $values['remark'],
			   			 'fund_id' => $values['bid'],
			   			 'user_id' => $user->uid,
			   			 'time_type' => 0,
			   			 'file_managed_id' => $fid,
			  			))->execute();
				  if ($last_id!=NULL) {
				     
					 $form_state['redirect'] = 'custodian_bank/guidingfund/'.$values['bid'];
					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
			/*}
			else{
				if($file_managed_id>0){
					$file = file_load($file_managed_id);
				  if($file!=NULL){
					 file_delete($file);
				  }
					db_delete('file_managed')
				    ->condition('fid',$file_managed_id)
					->execute();
				}	
				db_update('custodian_bank_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'remark' => $values['remark'],
			   			 'fund_id' => $values['bid'],
			   			 'file_managed_id' => $fid,
			  			))
			  		->condition('id',$uploadid)
			  		->execute();
				$form_state['redirect'] = 'custodian_bank/guidingfund/'.$values['bid'];
			}*/
			
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function custodian_bank_create_bannian_page($perid){
	 drupal_set_title('托管银行半年度报告提交');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('custodian_bank_create_bannian_form',$perid);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function custodian_bank_create_bannian_form($form, &$form_state, $perid){
	 $form['bid'] = array('#type' => 'hidden', '#value' => $perid);	 
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '托管银行半年度报告',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx'),
		'file_validate_size' => array(20*1024*1024)),
	);
	//if(!user_access('upload fund template file')){
		
	$form['upload_name'] = array(
	  '#title' => t('提交人：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	//}
	
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function custodian_bank_create_bannian_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
			//$type = 1;
			$query = "SELECT id, name FROM " .
		           "{guiding_fund_info} where id = ? ";
		    $queryResult = db_query($query, array($values['bid'] ));
			$fundname = '';
			
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$fundname = $links->name;
				}
			}
			$upload_name = '';
			$filename .= $fundname."_托管银行半年度报告";
			$upload_name = $values['upload_name'];

			$query = "SELECT id,file_managed_id FROM " .
		           "{custodian_bank_file_info} where fund_id = ? and time_type =? ";
		    $file_managed_id = '';  //已上传托管银行报告在file_managed表中对应的id
		    $queryResult = db_query($query, array($values['bid'],1));
			$uploadid = 0; //已上传托管银行报告id
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$file_managed_id = $links->file_managed_id;
					$uploadid = $links->id;
				}
			}
			if($uploadid==0){
				$last_id = db_insert('custodian_bank_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $upload_name,
			   			 'remark' => $values['remark'],
			   			 'fund_id' => $values['bid'],
			   			 'user_id' => $user->uid,
			   			 'time_type' => 1,
			   			 'file_managed_id' => $fid,
			  			))->execute();
				  if ($last_id!=NULL) {
					 $form_state['redirect'] = 'custodian_bank/guidingfund/'.$values['bid'];
					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
			}
			else{
				if($file_managed_id>0){
					$file = file_load($file_managed_id);
				  if($file!=NULL){
					 file_delete($file);
				  }
					db_delete('file_managed')
				    ->condition('fid',$file_managed_id)
					->execute();
				}	
				db_update('custodian_bank_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'remark' => $values['remark'],
			   			 'fund_id' => $values['bid'],
			   			 'file_managed_id' => $fid,
			  			))
			  		->condition('id',$uploadid)
			  		->execute();
				$form_state['redirect'] = 'custodian_bank/guidingfund/'.$values['bid'];
			}
			
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function custodian_bank_create_niandu_page($perid){
	 drupal_set_title('托管银行年度报告提交');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('custodian_bank_create_niandu_form',$perid);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function custodian_bank_create_niandu_form($form, &$form_state, $perid){
	 $form['bid'] = array('#type' => 'hidden', '#value' => $perid);	 
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '托管银行年度报告',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx'),
		'file_validate_size' => array(20*1024*1024)),
	);
	//if(!user_access('upload fund template file')){
		
	$form['upload_name'] = array(
	  '#title' => t('提交人：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	//}
	
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function custodian_bank_create_niandu_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
			//$type = 1;
			$query = "SELECT id, name FROM " .
		           "{guiding_fund_info} where id = ? ";
		    $queryResult = db_query($query, array($values['bid'] ));
			$fundname = '';
			
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$fundname = $links->name;
				}
			}
			$upload_name = '';
			$filename .= $fundname."_托管银行年度报告";
			$upload_name = $values['upload_name'];

			$query = "SELECT id,file_managed_id FROM " .
		           "{custodian_bank_file_info} where fund_id = ? and time_type =?";
		    $file_managed_id = '';  //已上传托管银行报告在file_managed表中对应的id
		    $queryResult = db_query($query, array($values['bid'],2));
			$uploadid = 0; //已上传托管银行报告id
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$file_managed_id = $links->file_managed_id;
					$uploadid = $links->id;
				}
			}
			if($uploadid==0){
				$last_id = db_insert('custodian_bank_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $upload_name,
			   			 'remark' => $values['remark'],
			   			 'fund_id' => $values['bid'],
			   			 'user_id' => $user->uid,
			   			 'time_type' => 2,
			   			 'file_managed_id' => $fid,
			  			))->execute();
				  if ($last_id!=NULL) {
				    
					 $form_state['redirect'] = 'custodian_bank/guidingfund/'.$values['bid'];
					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
			}
			else{
				if($file_managed_id>0){
					$file = file_load($file_managed_id);
				  if($file!=NULL){
					 file_delete($file);
				  }
					db_delete('file_managed')
				    ->condition('fid',$file_managed_id)
					->execute();
				}	
				db_update('custodian_bank_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'remark' => $values['remark'],
			   			 'fund_id' => $values['bid'],
			   			 'file_managed_id' => $fid,
			  			))
			  		->condition('id',$uploadid)
			  		->execute();
				
				$form_state['redirect'] = 'custodian_bank/guidingfund/'.$values['bid'];
			}
			
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function custodian_bank_create_churukuan_page($perid){
	 drupal_set_title('托管银行出入款资料提交');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('custodian_bank_create_churukuan_form',$perid);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function custodian_bank_create_churukuan_form($form, &$form_state, $perid){
	 $form['bid'] = array('#type' => 'hidden', '#value' => $perid);	 
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '托管银行出入款资料',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx'),
		'file_validate_size' => array(20*1024*1024)),
	);
	//if(!user_access('upload fund template file')){
		
	$form['upload_name'] = array(
	  '#title' => t('提交人：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	//}
	
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function custodian_bank_create_churukuan_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
			//$type = 1;
			$query = "SELECT id, name FROM " .
		           "{guiding_fund_info} where id = ? ";
		    $queryResult = db_query($query, array($values['bid'] ));
			$fundname = '';
			
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$fundname = $links->name;
				}
			}
			$upload_name = '';
			$filename .= $fundname."_托管银行出入款资料";
			$upload_name = $values['upload_name'];
			$query = "SELECT id,file_managed_id FROM " .
		           "{custodian_bank_file_info} where fund_id = ? and time_type =? ";
		    $file_managed_id = '';  //已上传托管银行报告在file_managed表中对应的id
		    $queryResult = db_query($query, array($values['bid'],3));
			$uploadid = 0; //已上传托管银行报告id
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$file_managed_id = $links->file_managed_id;
					$uploadid = $links->id;
				}
			}
			if($uploadid==0){
				$last_id = db_insert('custodian_bank_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $upload_name,
			   			 'remark' => $values['remark'],
			   			 'fund_id' => $values['bid'],
			   			 'user_id' => $user->uid,
			   			 'time_type' => 3,
			   			 'file_managed_id' => $fid,
			  			))->execute();
				  if ($last_id!=NULL) {
				    
					 $form_state['redirect'] = 'custodian_bank/guidingfund/'.$values['bid'];
					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
			}
			else{
				if($file_managed_id>0){
					$file = file_load($file_managed_id);
				  if($file!=NULL){
					 file_delete($file);
				  }
					db_delete('file_managed')
				    ->condition('fid',$file_managed_id)
					->execute();
				}	
				db_update('custodian_bank_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'remark' => $values['remark'],
			   			 'fund_id' => $values['bid'],
			   			 'file_managed_id' => $fid,
			  			))
			  		->condition('id',$uploadid)
			  		->execute();
				
				$form_state['redirect'] = 'custodian_bank/guidingfund/'.$values['bid'];
			}
			
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function custodian_bank_file_perpage($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;
  $query = "SELECT id, name,url,timestamp,remark, fund_id,user_id,upload_name FROM " .
           "{custodian_bank_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  foreach ($queryResult as $links ) {
    $page_content .= l('返回基金列表','custodian_bank/guidingfund/'.$links->fund_id) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';

	$page_content .= l('切换成编辑模式','custodian_bank/edit/'.$perid)  . '<br />'. '<br />';	

    $page_content .= '<h5>托管银行报告下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/drupal/sites/default/files/'.$links->url).'<br />'.'<br />';
    $page_content .= '<h5>提交人:</h5>'.$links->upload_name.'<br />'.'<br />';
	$page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'Y-m-d').'<br />'.'<br />';
    $page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';	
  }
  // More coming....
  if ($page_content == '') {
    $page_content = "没有该上传托管银行报告信息.";
  }

  return $page_content;
}

//传入fund_id
function custodian_bank_guidingfund_page($fund_id) {
  // content variable that will be returned for display
  $html = '';
  $html .= l('返回基金列表','custodian_bank/fundlist') . '<br />'. '<br />';
  $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
  $html .=  l('上传季度报告','custodian_bank/create_jidu/'.$fund_id). '<br />';  
  
  $header = array(
      array('data' => '季度报告'),
      array('data' => '提交人'),
      array('data' => '上传时间'),
      array('data' => '备注'),
      );
  $query = db_select('custodian_bank_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=')
	  ->condition('time_type',0,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'custodian_bank/list/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有提交记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
 
  $html .=  l('上传半年度报告','custodian_bank/create_bannian/'.$fund_id). '<br />';  
  $header = array(
      array('data' => '半年度报告'),
      array('data' => '提交人'),
      array('data' => '上传时间'),
      array('data' => '备注'),
      );
  $query = db_select('custodian_bank_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=')
	  ->condition('time_type',1,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'custodian_bank/list/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  $html .=  l('上传年度报告','custodian_bank/create_niandu/'.$fund_id). '<br />';
  $header = array(
      array('data' => '年度报告'),
      array('data' => '提交人'),
      array('data' => '上传时间'),
      array('data' => '备注'),
      );
  $query = db_select('custodian_bank_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=')
	  ->condition('time_type',2,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'custodian_bank/list/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  $html .=  l('上传出入款资料','custodian_bank/create_churukuan/'.$fund_id). '<br />';
  $header = array(
      array('data' => '出入款资料'),
      array('data' => '提交人'),
      array('data' => '上传时间'),
      array('data' => '备注'),
      );
  $query = db_select('custodian_bank_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=')
	  ->condition('time_type',3,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'custodian_bank/list/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' =>'没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function custodian_bank_edit_perpage($perid) {
  $page_content = '';
  //$page_content .= l('查看基金信息','guidingfund/list/') . '<br />'. '<br />';
  $page_content .= l('切换成浏览模式','custodian_bank/list/'.$perid) . '<br />'. '<br />'; 	
  drupal_set_title('托管银行资料管理');
	 
  $query = "SELECT id,name, url FROM " .
           "{custodian_bank_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0){
	  	  $ifempty = FALSE;
	  }	  
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('custodian_bank_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{

	 	$page_content .= '<h5>已提交托管银行资料:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/drupal/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('custodian_bank_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function custodian_bank_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark, fund_id,user_id,upload_name,file_managed_id FROM " .
           "{custodian_bank_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $reply_remark = '';
  $fund_id = '';
  $type = '';
  $upload_name = '';
  global $user;
  foreach ($queryResult as $links ) {
  	
	$name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
	$fund_id =  $links->fund_id;
  	$upload_name = $links->upload_name;
	$file_managed_id = $links->file_managed_id;
  }

   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
	$form['fund_id'] = array('#type' => 'hidden', '#value' => $fund_id);
	
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['custodian_bank_edit_form']['name'])?$_SESSION['custodian_bank_edit_form']['name']:$name,
	 );
	 
    $form['upload_name'] = array(
	  '#title' => t('提交人'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['custodian_bank_edit_form']['upload_name'])?$_SESSION['custodian_bank_edit_form']['upload_name']:$upload_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交托管银行报告',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['custodian_bank_edit_form']['remark'])?$_SESSION['custodian_bank_edit_form']['remark']:$remark,
	 );
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该报告'),
	    '#submit' => array('custodian_bank_edit_form_deleate'),
	  );  
	  
   return $form;
}

function custodian_bank_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	
	global $user; 
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	

				db_update('custodian_bank_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'file_managed_id' => $fid,
			   	    'upload_name' => $values['upload_name'],
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
					
			$form_state['redirect'] = 'custodian_bank/list/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
				db_update('custodian_bank_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'upload_name' => $values['upload_name'],
			  		))
			  		->condition('id',$uploadid)
			  		->execute();									
			$form_state['redirect'] = 'custodian_bank/list/'.$values['bid'];
	}
}

function custodian_bank_edit_form_deleate($form, &$form_state){
	 $values = NULL;
	 $_SESSION['custodian_bank_edit_form'] = $form_state['values'];
	 $values = $_SESSION['custodian_bank_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'custodian_bank/deleate/'.$values['bid'];
}

function custodian_bank_deleate_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后申报内容将不可恢复！';
  
  drupal_set_title('删除申报内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('custodian_bank_deleate_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function custodian_bank_deleate_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('custodian_bank_deleate_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function custodian_bank_deleate_form_back($form, &$form_state){
	if(empty($_SESSION['custodian_bank_edit_form'])){
		  	$form_state['redirect'] = 'custodian_bank/list';
	  }else{
		  $values = $_SESSION['custodian_bank_edit_form'];
		  unset($_SESSION['custodian_bank_edit_form']);
		  $form_state['redirect'] = 'custodian_bank/edit/'.$values['bid'];
	  }
}

function custodian_bank_deleate_form_submit($form, &$form_state){
 if(empty($_SESSION['custodian_bank_edit_form'])){
		  	$form_state['redirect'] = 'guidingfund/list';
	  }else{
		  $values = $_SESSION['custodian_bank_edit_form'];
		  unset($_SESSION['custodian_bank_edit_form']);
		  
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('custodian_bank_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'guidingfund/list';

	  }

}

//托管银行资料提交管理基金选择入口
function custodian_bank_fundlist_page() {
 $html = '';
 global $user; 
 if(user_access('view custodian bank info'))
 	drupal_goto('guidingfund/custodian_bankchoose_page');
 else if(user_access('create custodian bank info')){
 	$bankid = '';
 	$header = array(
      array('data' => '银行名称'),
      array('data' => '负责人'),
      array('data' => '联系电话'),
      array('data' => '手机'),
      array('data' => '邮箱'),
      array('data' => '负责人职位'),
      array('data' => '备注'),
      );
	  $query = db_select('custodian_bank_info', 'n')
	      ->extend('PagerDefault') //Pager Extender
	      ->limit(15)//10 results per page
	      ->extend('TableSort')//Sorting Extender
	      ->orderByHeader($header)//Field to sort on is picked from $header
	      ->fields ('n', array (
	      'id',
	      'bank_name',
	      'principal_name',
	      'phone',
	      'mobile',
	      'mail',
	      'position',
	      'remark'
	      ))
		  ->condition('user_id',$user->uid,'=');
	  $results = $query
	      ->execute();
	
	  $rows = array();
	  foreach ($results as $node) {
	  		  $bankid = $node->id;
	          $title = l('编辑', 'custodian_bank_info/edit/'.$node->id);
			  $rows[] = array(
		      'data' => array(
		        l($node->bank_name, 'custodian_bank_info/edit/'. $node->id),
		        $node->principal_name,
		        $node->phone,
		        $node->mobile,
		        $node->mail,
		        $node->position,
		        $node->remark,
		      )
		      );
	  }
	  $html .= theme('table', 
	      array(
	            'header' => $header,
	            'rows'=>$rows,
	            //'caption' => '反馈意见列表',//Optional Caption for the table
	            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
	            'empty' => l('请填写银行信息','custodian_bank_info/create'),//Optional empty text for the table if resultset is empty
	      )
	      );
	  $html .= theme('pager',
	      array(
	            'tags' => array()
	      )
	      );

 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '托管银行资料管理', 'field' => 'info_set'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'timestamp',
      'custodian_bank_list',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {

		  $custodian_banks = array();
		  $custodian_banks = explode(',',$node->custodian_bank_list);
  		 if(in_array($bankid,$custodian_banks, TRUE)&&$custodian_banks!=NULL&&$bankid!=''){
          $title = l('资料提交管理', 'custodian_bank/guidingfund/'.$node->id);
		  $rows[] = array(
	      'data' => array(
	        $node->name, 
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'Y-m-d'),
	        $title,
	      )
	      );
		}
  }
  if($bankid==''){
  	 $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => l('请填写银行信息','custodian_bank_info/create'),//Optional empty text for the table if resultset is empty
      )
      );
  }
  else{
  	 $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有托管基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  }
 
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  }
  return ($html); 
}

////////
//托管银行信息管理
////////
function custodian_bank_info_create_page(){
	  //我们为这个页面设置标题
	 drupal_set_title('托管银行信息管理');
	 global $user;  
	 
	 $query = "SELECT id FROM " .
           "{custodian_bank_info} where user_id = ?";
 	 $queryResult = db_query($query, array($user->uid));
	 $ifempty =TRUE;
	 $pageid ='';
	  foreach ($queryResult as $links ) {
	  	$pageid =$links->id;
	  	if($pageid > 0)
		  	$ifempty = FALSE;
	  }
	 if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('custodian_bank_info_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
	 else{
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		$form = drupal_get_form('custodian_bank_info_edit_form',$pageid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function custodian_bank_info_create_form(){	 
	  //提示信息，默认为markup类型。
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['bank_name'] = array(
	  '#title' => t('银行名称'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['custodian_bank_info_create_form']['bank_name'])?$_SESSION['custodian_bank_info_create_form']['bank_name']:"",
	 );
	 
	 $form['principal_name'] = array(
	  '#title' => t('负责人名称'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['custodian_bank_info_create_form']['principal_name'])?$_SESSION['custodian_bank_info_create_form']['principal_name']:"",
	 );
	 
	 $form['phone'] = array(
	  '#title' => t('联系电话'),
	  '#type' => 'textfield',
	  '#required' => false,
	  '#default_value' =>isset($_SESSION['custodian_bank_info_create_form']['phone'])?$_SESSION['custodian_bank_info_create_form']['phone']:"",
	 );
	  $form['mobile'] = array(
	  '#title' => t('手机'),
	  '#type' => 'textfield',
	  '#required' => false,
	  '#default_value' =>isset($_SESSION['custodian_bank_info_create_form']['mobile'])?$_SESSION['custodian_bank_info_create_form']['mobile']:"",
	 );
	 
	  $form['mail'] = array(
	  '#title' => t('邮箱地址'),
	  '#type' => 'textfield',
	  '#required' => false,
	  '#default_value' =>isset($_SESSION['custodian_bank_info_create_form']['mail'])?$_SESSION['custodian_bank_info_create_form']['mail']:"",
	 );
	 
	  $form['position'] = array(
	  '#title' => t('负责人职位'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['custodian_bank_info_create_form']['position'])?$_SESSION['custodian_bank_info_create_form']['position']:"",
	 );
	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['custodian_bank_info_create_form']['remark'])?$_SESSION['custodian_bank_info_create_form']['remark']:"",
	 );
	 	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function custodian_bank_info_create_form_validate($form, &$form_state){
	 if(!preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $form_state['values']['mail'])){
	  form_set_error('mail',t('您输入的电子邮件地址格式不正确'));
	 }
	  if (drupal_strlen($form_state['values']['principal_name']) < 2) {
	    form_set_error('principal_name', '您输入的负责人姓名长度太短，请填写真实姓名。');
	  }
  
}

function custodian_bank_info_create_form_submit($form, &$form_state){
	  //把表单的值存放在会话中去，由于这里涉及到了两个不同的表单之间传值。
	 $_SESSION['custodian_bank_info_create_form'] = $form_state['values'];
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'custodian_bank_info/create/confirm';
}

function custodian_bank_info_confirm_page(){
  //我们为这个页面设置标题
	 drupal_set_title('提交托管银行信息预览');
	 
	 //这里首先作了判断，如果会话中没有设置contactus_form，返回contactus
	 if(empty($_SESSION['custodian_bank_info_create_form'])){
	  drupal_goto('custodian_bank_info/create');
	 }
	 $render_array = array(
	   '#markup' => '', 
	 );
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('custodian_bank_info_confirm_form');
	 $render_array['#markup'] .= drupal_render($form);
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function custodian_bank_info_confirm_form(){
 $form['bank_name'] = array(
  '#title' => t('银行名称'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['custodian_bank_info_create_form']['bank_name'])?$_SESSION['custodian_bank_info_create_form']['bank_name']:"",
 );
 
 $form['principal_name'] = array(
  '#title' => t('负责人名称'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['custodian_bank_info_create_form']['principal_name'])?$_SESSION['custodian_bank_info_create_form']['principal_name']:"",
 );
 
 $form['phone'] = array(
  '#title' => t('联系电话'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['custodian_bank_info_create_form']['phone'])?$_SESSION['custodian_bank_info_create_form']['phone']:"",
 );
 
 $form['mobile'] = array(
  '#title' => t('移动电话'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['custodian_bank_info_create_form']['mobile'])?$_SESSION['custodian_bank_info_create_form']['mobile']:"",
 );
 
 $form['mail'] = array(
  '#title' => t('邮箱地址'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['custodian_bank_info_create_form']['mail'])?$_SESSION['custodian_bank_info_create_form']['mail']:"",
 );
 
 $form['position'] = array(
  '#title' => t('负责人职位'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['custodian_bank_info_create_form']['position'])?$_SESSION['custodian_bank_info_create_form']['position']:"",
 );
 
 $form['remark'] = array(
  '#title' => t('备注'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['custodian_bank_info_create_form']['remark'])?$_SESSION['custodian_bank_info_create_form']['remark']:"",
 );
  
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('返回'),
    '#submit' => array('custodian_bank_confirm_form_back'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('提交'),
  );
  
  return $form;
}

function custodian_bank_info_confirm_form_back($form, &$form_state){
  //简单的重定向到contactus页面
 $form_state['redirect'] = 'custodian_bank_info/create';
}

function custodian_bank_info_confirm_form_submit($form, &$form_state){
		/**
	   * 写入数据库
	   */
	   $values = NULL;
	   //从会话中获取用户最初提交的值，并将$_SESSION['contactus_form']置为空。
	  if(empty($_SESSION['custodian_bank_info_create_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'custodian_bank_info/create';
	  }else{
		  $values = $_SESSION['custodian_bank_info_create_form'];
		  unset($_SESSION['custodian_bank_info_create_form']);
	  }
	  global $user;
	  $last_id = db_insert('custodian_bank_info')
  		->fields(array(
  		     'user_id'=> $user->uid,
   			 'bank_name' => $values['bank_name'],
   			 'principal_name' => $values['principal_name'],
   			 'phone' => $values['phone'],
   			 'mobile' =>  $values['mobile'],
   			 'mail' => $values['mail'],
   			 'position' =>  $values['position'],
   			 'remark' => $values['remark'],
  			))->execute();
	  if ($last_id!=NULL) {	
		 $form_state['redirect'] = 'custodian_bank_info/edit/'.$last_id;	 	    
	  } else {
	    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');	    
	  }	
}

function custodian_bank_info_list_page() {
 $html = '';
 $html .= l('基金托管银行设置','guidingfund/custodian_bankchoose_page'). '<br><br>';
 
 $header = array(
      array('data' => '银行名称', 'field' => 'bank_name', 'sort' => 'desc'),
      array('data' => '负责人名称', 'field' => 'principal_name'),
      array('data' => '电话', 'field' => 'phone'),
      array('data' => '手机', 'field' => 'mobile'),
      array('data' => '邮箱', 'field' => 'mail'),
      array('data' => '职务', 'field' => 'position'),
      array('data' => '备注', 'field' => 'remark'),
      );
  $query = db_select('custodian_bank_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'bank_name',
      'principal_name',
      'position',
      'phone',
      'mail',
      'mobile',
      'remark',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->bank_name, 'custodian_bank_info/edit/'. $node->id),
        $node->principal_name,
        $node->phone,
        $node->mobile,
        $node->mail,
        $node->position,
        $node->remark,
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有托管银行信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function custodian_bank_info_list_perpage($perid) {
  // content variable that will be returned for display
  $page_content = '';
  $page_content .= l('查看托管银行信息列表','custodian_bank_info/list') . '<br />'. '<br />';
  
  $query = "SELECT bank_name,principal_name,phone,mobile,mail,position,remark FROM " .
           "{custodian_bank_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  foreach ($queryResult as $links ) { 
    $page_content .= '<h5>银行名称：'.$links->bank_name.'</h5><br />';
	$page_content .= '<h5>负责人名称：'.$links->principal_name.'</h5><br />';
	$page_content .= '<h5>联系电话：'.$links->phone.'</h5><br />';
	$page_content .= '<h5>手机：'.$links->mobile.'</h5><br />';
	$page_content .= '<h5>邮箱地址：'.$links->mail.'</h5><br />';
	$page_content .= '<h5>职务'.$links->position.'</h5><br />';
    $page_content .= '<h5>备注：'.$links->remark.'</h5><br />';
	$page_content = str_replace(array("\n", "\r\n") , "<BR />", $page_content);
  }
  // More coming....
  if ($page_content == '') {
    $page_content = "没有该托管银行信息.";
  }

  return $page_content;
}

function custodian_bank_info_edit_page($perid) {
  $page_content = '';
  if(user_access('view custodian bank info'))
  	$page_content .= l('查看托管银行信息列表','custodian_bank_info/list') . '<br />'. '<br />';
  drupal_set_title('托管银行信息管理');
	 
	 $query = "SELECT id FROM " .
           "{custodian_bank_info} where id = ?";
 	 $queryResult = db_query($query, array($perid));
	 $ifempty =TRUE;
	  foreach ($queryResult as $links ) {
	  	if($links->id>0)
		  	$ifempty = FALSE;
	  }
	 if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('custodian_bank_info_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
	 else{
	 	 $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('custodian_bank_info_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function custodian_bank_info_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT bank_name,principal_name,phone,mobile,mail,position,remark  FROM " .
           "{custodian_bank_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $bank_name = '';
  $principal_name = '';
  $phone = '';
  $mobile = '';
  $mail = ''; 
  $position = '';
  $remark = '';
  
  foreach ($queryResult as $links ) {
  	$bank_name = $links->bank_name;
    $principal_name = $links->principal_name;
	$phone = $links->phone;
	$mobile = $links->mobile;
    $mail = $links->mail;
	$position = $links->position;
	$remark = $links->remark;
  }
   $form['bid'] = array('#type' => 'hidden', '#value' => $perid);
   $form['bank_name'] = array(
	  '#title' => t('银行名称'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['custodian_bank_info_edit_form']['bank_name'])?$_SESSION['custodian_bank_info_edit_form']['bank_name']:$bank_name,
	 );
	 
	 $form['principal_name'] = array(
	  '#title' => t('负责人名称'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['custodian_bank_info_edit_form']['principal_name'])?$_SESSION['custodian_bank_info_edit_form']['principal_name']:$principal_name,
	 );
	 
     $form['phone'] = array(
	  '#title' => t('联系电话'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['custodian_bank_info_edit_form']['phone'])?$_SESSION['custodian_bank_info_edit_form']['phone']:$phone,
	 );
  	 $form['mobile'] = array(
	  '#title' => t('手机'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['custodian_bank_info_edit_form']['mobile'])?$_SESSION['custodian_bank_info_edit_form']['mobile']:$mobile,
	 );
	 $form['mail'] = array(
	  '#title' => t('邮箱地址'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['custodian_bank_info_edit_form']['mail'])?$_SESSION['custodian_bank_info_edit_form']['mail']:$mail,
	 );
	 
	 $form['position'] = array(
	  '#title' => t('职务'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['custodian_bank_info_edit_form']['position'])?$_SESSION['custodian_bank_info_edit_form']['position']:$position,
	 );
	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['custodian_bank_info_edit_form']['remark'])?$_SESSION['custodian_bank_info_edit_form']['remark']:$remark,
	 );
	
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除托管银行信息'),
	    '#submit' => array('custodian_bank_info_edit_form_deleate'),
	  );
  return $form;
}

function custodian_bank_info_edit_form_submit($form, &$form_state){
	  $values = NULL;
	  $values = $form_state['values'];		
	  db_update('custodian_bank_info')
  		->fields(array(
   			 'bank_name' => $values['bank_name'],
   			 'principal_name' => $values['principal_name'],
   			 'phone' => $values['phone'],
   			 'mobile' => $values['mobile'],
   			 'mail' => $values['mail'],
   			 'position' =>  $values['position'],
   			 'remark' =>  $values['remark'],
  			))
  		->condition('id', $values['bid'])
  		->execute();
	 $form_state['redirect'] = 'custodian_bank_info/edit/'.$values['bid'];
}

function custodian_bank_info_edit_form_deleate($form, &$form_state){
	 $values = NULL;
	 $_SESSION['custodian_bank_info_edit_form'] = $form_state['values'];
	 $values = $_SESSION['custodian_bank_info_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'custodian_bank_info/deleate/'.$values['bid'];
}

function custodian_bank_info_deleate_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后托管银行信息将不可恢复！';
  
  drupal_set_title('删除托管银行信息');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('custodian_bank_info_deleate_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function custodian_bank_info_deleate_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('custodian_bank_info_deleate_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function custodian_bank_info_deleate_form_back($form, &$form_state){
	if(empty($_SESSION['custodian_bank_info_edit_form'])){
		  if(user_access('view custodian bank info'))
		  	$form_state['redirect'] = 'custodian_bank_info/list';
		  else{
		  	$form_state['redirect'] = 'custodian_bank_info/create';
		  }
	  }else{
		  $values = $_SESSION['custodian_bank_info_edit_form'];
		  unset($_SESSION['custodian_bank_info_edit_form']);
		  $form_state['redirect'] = 'custodian_bank_info/edit/'.$values['bid'];
	  }
}

function custodian_bank_info_deleate_form_submit($form, &$form_state){
  //简单的重定向到contactus页面
 if(empty($_SESSION['custodian_bank_info_edit_form'])){
		  //drupal_goto('contact');
		   if(user_access('view custodian bank info'))
		  	$form_state['redirect'] = 'custodian_bank_info/list';
		  else{
		  	$form_state['redirect'] = 'custodian_bank_info/create';
		  }
	  }else{
		  $values = $_SESSION['custodian_bank_info_edit_form'];
		  unset($_SESSION['custodian_bank_info_edit_form']);
		  db_delete('custodian_bank_info')
			->condition('id' ,$values['bid'])
			->execute();
		  if(user_access('view custodian bank info'))
		  	$form_state['redirect'] = 'custodian_bank_info/list';
		  else
		  	$form_state['redirect'] = 'custodian_bank_info/create';
	  }

}

function custodian_bank_info_choose_page($perid) {
  drupal_set_title('托管银行选择管理');
  $page_content = '';
  $page_content .= l('返回基金列表','guidingfund/custodian_bankchoose_page') . '<br />'. '<br />';

  //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
  $render_array = array(
  		'#markup' => $page_content,
  );
  $form = drupal_get_form('custodian_bank_info_choose_form', $perid);
  $render_array['#markup'] .= drupal_render($form ); 
  
  return $render_array; 
}
//传人fundid
function custodian_bank_info_choose_form($form, &$form_state, $fundid){
  $query = "SELECT custodian_bank_list FROM " .
           "{guiding_fund_info} where id = ?";
  $custodian_banks_list = db_query($query, array($fundid));	
  $custodian_banks = array();
  foreach ($custodian_banks_list as $custodian_bank) {
      $custodian_banks = explode(',',$custodian_bank->custodian_bank_list);
  }
  $query = "SELECT id,bank_name, principal_name, position,remark FROM " .
           "{custodian_bank_info}";
  $queryResult = db_query($query);	
  
  $header = array(
    'bank_name' => t('银行名称'),
    'principal_name' => t('负责人'),
    'position' => t('职务'),
    'remark' => t('备注'),
    'state' => t('状态(空表示未被选择)'),
  );
  $options = array();
  foreach ($queryResult as $node) {
  	$state = '';
  	if(in_array($node->id,$custodian_banks, TRUE)&&$custodian_banks!=NULL){
  		$state=  '已选择';
  	}
    $options[$node->id] =array(
      'bank_name' => l($node->bank_name, 'custodian_bank_info/list/'. $node->id),
      'principal_name' => $node->principal_name,
      'position' => $node->position,
      'remark' => $node->remark,
      'state' => $state,   
    );
  }
  $form['bid'] = array('#type' => 'hidden', '#value' => $fundid);
  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('没有托管银行记录'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('提交'),
  );
  return $form;  
}

function custodian_bank_info_choose_form_submit($form, &$form_state){
	 $values = NULL;
	 $values = $form_state['values'];		
	 $custodian_banks_list = '';
	 foreach ($values['table'] as $rows) {
         $custodian_banks_list.=$rows.',';
     }
	  db_update('guiding_fund_info')
  		->fields(array(
   			 'custodian_bank_list' => $custodian_banks_list,
  			))
  		->condition('id', $values['bid'])
  		->execute();
	 $form_state['redirect'] = 'custodian_bank_info/choose/'.$values['bid'];	
	 
}

//////////
//被投企业资本退出
//////////
function company_exit_create($qiye_id){
	  //我们为这个页面设置标题
	 drupal_set_title('新增资本退出信息');
	 $page_content = '';
	 $query = "SELECT fund_id FROM " .
           "{beitouqiye_info} where id = ?";
    $queryResult = db_query($query, array($qiye_id));
    foreach ($queryResult as $result) {
       $page_content .= l('返回企业列表','qiye_tcbg_file/qiye/'.$result->fund_id) . '<br />'. '<br />';    
    }
	 //$page_content = l('返回企业列表','qiye_tcbg_file/qiye/'.$qiye_id) . '<br />'. '<br />';
	 $render_array = array(
	   '#markup' => $page_content, 
	 );
	 
	 $form = drupal_get_form('company_exit_form',$qiye_id);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function company_exit_form($form, &$form_state, $qiye_id){
	 $form['bid'] = array('#type' => 'hidden', '#value' => $qiye_id);
	 
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['exit_money'] = array(
	  '#title' => t('资本退出金额（万元）'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['company_exit_form']['exit_money'])?$_SESSION['company_exit_form']['exit_money']:"",
	  //'#description' => t('例如：250.55'),
	 );
	 $today = getdate();
     $form['exit_timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('退出时间'),
	     '#default_value' => array('year' =>  $today['year'], 'month' =>  $today['mon'], 'day' => $today['mday']), 
	 );
	 $form['exit_type'] = array(
	  '#title' => t('退出方式'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['company_exit_form']['exit_type'])?$_SESSION['company_exit_form']['exit_type']:"",
	 ); 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['company_exit_form']['remark'])?$_SESSION['company_exit_form']['remark']:"",
	 );
	
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认退出'),
	  );
	  return $form;
}

function company_exit_form_validate($form, &$form_state){
	  if (drupal_strlen($form_state['values']['exit_money']) > 15) {
	    form_set_error('exit_money', '要求精度小于15 个字符');
	  } 
	  if (!($form_state['values']['exit_money']>=0)) {
	    form_set_error('exit_money', '请输入正数');
	  }  
}

function company_exit_form_submit($form, &$form_state){
	  //把表单的值存放在会话中去，由于这里涉及到了两个不同的表单之间传值。
	 $_SESSION['company_exit_form'] = $form_state['values'];
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'company_exit/confirm';
}
 
function company_exit_confirm_page(){
  //我们为这个页面设置标题
	 drupal_set_title('新增资本退出信息');
	 
	 //这里首先作了判断，如果会话中没有设置contactus_form，返回contactus
	 if(empty($_SESSION['company_exit_form'])){
	  drupal_goto('qiye_tcbg_file/fundlist');
	 }	
	 $render_array = array(
	   '#markup' => '', 
	 );
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('company_exit_confirm_form');
	 $render_array['#markup'] .= drupal_render($form);
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function company_exit_confirm_form(){
     
     $form['exit_money'] = array(
	  '#title' => t('资本退出金额（万元）'),
	  '#type' => 'item',
	  '#markup' =>isset($_SESSION['company_exit_form']['exit_money'])?$_SESSION['company_exit_form']['exit_money']:"",
	 );
	 $exit_timestamp = $_SESSION['company_exit_form']['exit_timestamp'];
     $form['exit_timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('退出时间'),
	     '#markup' => isset($_SESSION['company_exit_form']['exit_timestamp'])?$exit_timestamp['year'].'年'.$exit_timestamp['month'].'月'.$exit_timestamp['day'].'日':"", 
	 );
	 $form['exit_type'] = array(
	  '#title' => t('退出方式'),
	  '#type' => 'item',
	  '#markup' =>isset($_SESSION['company_exit_form']['exit_type'])?$_SESSION['company_exit_form']['exit_type']:"",
	 ); 
	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'item',
	  '#markup' =>isset($_SESSION['company_exit_form']['remark'])?$_SESSION['company_exit_form']['remark']:"",
	 );

	  $form['back'] = array(
	    '#type' => 'submit',
	    '#value' => t('返回'),
	    '#submit' => array('company_exit_confirm_form_back'),
	  );
	
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交'),
	  );
	  
	  return $form;
}

function company_exit_confirm_form_back($form, &$form_state){
 $form_state['redirect'] = 'company_exit/create/'.$_SESSION['company_exit_form']['bid'];
}

function company_exit_confirm_form_submit($form, &$form_state){
		/**
	   * 写入数据库
	   */
	  $values = NULL;
	  global  $user;
	  if(empty($_SESSION['company_exit_form'])){
		  drupal_goto('company_exit/create/'.$values['bid']);
	  }else{
		  $values = $_SESSION['company_exit_form'];
		  unset($_SESSION['company_exit_form']);
	  }
      $exit_timestamp = mktime(0, 0, 0,$values['exit_timestamp']['month'], $values['exit_timestamp']['day'], $values['exit_timestamp']['year']);
	  $query = "SELECT fund_id FROM " .
           "{beitouqiye_info} where id = ?";
	  $queryResult = db_query($query, array($values['bid']));
	  $fund_id = '';
	  foreach ($queryResult as $result) {
	  	$fund_id = $result->fund_id;
	  }
	  $last_id = db_insert('company_exit_info')
  		->fields(array(
  		     'fund_id' => $fund_id,
  		     'beitouqiye_id' => $values['bid'],
   			 'exit_timestamp' => $exit_timestamp,  			 
   			 'exit_type' => $values['exit_type'],
   			 'exit_money' => $values['exit_money'],
   			 'remark' => $values['remark'],
  			))->execute();
	  if ($last_id!=NULL) {
		 $form_state['redirect'] = 'company_exit/list/'.$last_id;
	  } else {
	    
	    // 数据写入失败了
	    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
	    
	  }	
}

//传人资本退出id
function company_exit_exportcsv_perpage($qiye_id){
  $filename = '被投企业资本退出信息.csv' ;
  drupal_add_http_header('Content-Type', 'text/csv; charset=utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $filename . '"');
  $header = array(
      // iconv('utf-8','gb2312','序号'),
       iconv('utf-8','gb2312','基金名称'),
       iconv('utf-8','gb2312','企业名称'),
       iconv('utf-8','gb2312','投资时间'),
       iconv('utf-8','gb2312', '投资额（万元）'),
              
       iconv('utf-8','gb2312','退出时间'),
       iconv('utf-8','gb2312', '退出金额（万元）'),
       iconv('utf-8','gb2312', '退出方式'),
       iconv('utf-8','gb2312', '备注'),
      );
  print implode(',', $header) ."\r\n";
  $query = db_select('company_exit_info', 'n')
      ->fields ('n', array (
      'id',
      'company_name',
      'touzi_timestamp',
      'touzi_money',
      ))
	  ->condition('id',$qiye_id,'=');
  $results = $query
      ->execute();
  $serial_num = 1;
  foreach ($results as $node) {
      $touzi_timestamp = str_replace(array(',',",",'，',"，") , " ", format_date($node->touzi_timestamp, 'custom', 'Y-m-d'));
      $query = "SELECT fund_id,exit_timestamp,exit_type,exit_money,remark FROM " .
           "{company_exit_info} where beitouqiye_id = ?";
	  $queryResult = db_query($query, array($qiye_id));
	  $fund_id = '';
	  $exit_timestamp = '';
	  $exit_type = '';
	  $exit_money = '';
	  $remark = '';
	  foreach ($queryResult as $result) {
	  	$fund_id = $result->fund_id;
		$exit_timestamp = str_replace(array(',',",",'，',"，") , " ", format_date($result->exit_timestamp, 'custom', 'Y-m-d'));
		$exit_type = $result->exit_type;
		$exit_money = $result->exit_money;
		$remark = $result->remark;
	  }
	  
	  $query = "SELECT name FROM " .
           "{guiding_fund_info} where id = ?";
	  $queryResult = db_query($query, array($fund_id));
	  $fund_name = '';
	  foreach ($queryResult as $result) {
	  	$fund_name = $result->name;
	  }
      $values = array( $fund_name,$node->company_name, $touzi_timestamp, $node->touzi_money,
      	$exit_timestamp,$exit_money,$exit_type,$remark); 
	  $str = implode(',', $values) ."\r\n";
	  $str = iconv('utf-8','gb2312',$str);
	  print $str;
	  //$serial_num+=1;
    }  
}

function company_exit_exportcsv_page($fund_id){
  $filename = '被投企业资本退出信息.csv' ;
  drupal_add_http_header('Content-Type', 'text/csv; charset=utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $filename . '"');
  $header = array(
       iconv('utf-8','gb2312','序号'),
       iconv('utf-8','gb2312','基金名称'),
       iconv('utf-8','gb2312','企业名称'),
       iconv('utf-8','gb2312','投资时间'),
       iconv('utf-8','gb2312', '投资额（万元）'),
              
       iconv('utf-8','gb2312','退出时间'),
       iconv('utf-8','gb2312', '退出金额（万元）'),
       iconv('utf-8','gb2312', '退出方式'),
       iconv('utf-8','gb2312', '备注'),
      );
  print implode(',', $header) ."\r\n";
  $query = db_select('company_exit_info', 'n')
      ->fields ('n', array (
       'id',
      'company_name',
      'touzi_timestamp',
      'touzi_money', 
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();
  $serial_num = 1;
  $query = "SELECT name FROM " .
           "{guiding_fund_info} where id = ?"; 
  $queryResult = db_query($query, array($fund_id));
  $fund_name = '';
  foreach ($queryResult as $result) {
	  $fund_name = $result->name;
  }
  foreach ($results as $node) {
      $touzi_timestamp = str_replace(array(',',",",'，',"，") , " ", format_date($node->touzi_timestamp, 'custom', 'Y-m-d'));
      $query = "SELECT fund_id,exit_timestamp,exit_type,exit_money,remark FROM " .
           "{company_exit_info} where beitouqiye_id = ?";
	  $queryResult = db_query($query, array($node->id));
	  $fund_id = '';
	  $exit_timestamp = '';
	  $exit_type = '';
	  $exit_money = '';
	  $remark = '';
	  foreach ($queryResult as $result) {
	  	$fund_id = $result->fund_id;
		$exit_timestamp = str_replace(array(',',",",'，',"，") , " ", format_date($result->exit_timestamp, 'custom', 'Y-m-d'));
		$exit_type = $result->exit_type;
		$exit_money = $result->exit_money;
		$remark = $result->remark;
	  }
      $values = array($serial_num, $fund_name, $node->company_name, $touzi_timestamp, $node->touzi_money, $exit_timestamp, 
       $exit_money,$exit_type, $remark, ); 
	  $str = implode(',', $values) ."\r\n";
	  $str = iconv('utf-8','gb2312',$str);
	  print $str;
	  $serial_num+=1;
    }

  
}

//传人基金id
function company_exit_fundlist_perpage($fund_id) {
  $html = '';	
  $html .= l('返回基金列表','qiye_tcbg_file/fundlist') .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 
  $html .= l('导出','company_exit/exportcsv/'.$fund_id) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $options = array(
  'target_id' => 'printable_div',
  'value' => t('Print'),
  'type' => 'link',
  'custom_css' => drupal_get_path('module','my_module').'/css/print.css',
  );

  $html .= area_print_form($options). '<br />'. '<br />';
   $query = "SELECT name FROM " .
           "{guiding_fund_info} where id = ?"; 
  $queryResult = db_query($query, array($fund_id));
  $fund_name = '';
 
  foreach ($queryResult as $result) {
	  $fund_name = $result->name;
  }
   $html .= '当前基金：&nbsp;&nbsp;'.$fund_name. '<br />'. '<br />';
  
  $html .= '<div id="printable_div">';
  $round_num = 1;
  $header = array(
      array('data' => '序号'),
      array('data' => '企业名称', 'field' => 'company_name'),
      array('data' => '投资时间', 'field' => 'touzi_timestamp'),
      array('data' => '投资额(万元)', 'field' => 'touzi_money'),
      array('data' => '退出时间', 'field' => 'exit_timestamp'),
      array('data' => '退出金额（万元）', 'field' => 'exit_money'),
      array('data' => '退出方式', 'field' => 'exit_type'),
      array('data' => '详情'),
      );
  $query = db_select('beitouqiye_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(20)//20 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'company_name',
      'touzi_timestamp',
      'touzi_money',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  $_serial_num = 1;
  foreach ($results as $node) {
  	 $query = "SELECT fund_id,exit_timestamp,exit_type,exit_money FROM " .
           "{company_exit_info} where beitouqiye_id = ?";
	  $queryResult = db_query($query, array($node->id));
	  $fund_id = '';
	  $exit_timestamp = '';
	  $exit_type = '';
	  $exit_money = '';
	  foreach ($queryResult as $result) {
	  	$fund_id = $result->fund_id;
		$exit_timestamp = str_replace(array(',',",",'，',"，") , " ", format_date($result->exit_timestamp, 'custom', 'Y-m-d'));
		$exit_type = $result->exit_type;
		$exit_money = $result->exit_money;
	  }
      $rows[] = array(
      'data' => array(
        $_serial_num,
        l($node->company_name, 'company_exit/list/'. $node->id),
        format_date($node->touzi_timestamp, 'custom', 'Y-m-d'),
        $node->touzi_money,
        $exit_timestamp,
        $exit_money,
        $exit_type,
         l('查看', 'company_exit/list/'. $node->id),
      )
      );
	  $_serial_num++;
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有资本退出信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= '</div>';
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  
  return ($html); 
}
//传人资本退出id
function company_exit_per_page($perid) {
 
  // content variable that will be returned for display
  $page_content = '';
  $query = "SELECT fund_id FROM " .
           "{company_exit_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  foreach ($queryResult as $result) {
     $page_content .= l('返回企业列表','qiye_tcbg_file/qiye/'.$result->fund_id) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';     
  }
  $page_content .= l('导出','company_exit/exportcsv/per/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  drupal_set_title('管理该项资本退出信息');
  $options = array(
  'target_id' => 'printable_div',
  'value' => t('Print'),
  'type' => 'link',
  'custom_css' => drupal_get_path('module','my_module').'/css/print.css',
  );

  $page_content .= area_print_form($options). '<br />'. '<br />';
  
  $page_content .= '<div id="printable_div">';
  	 
  $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
  $form = drupal_get_form('company_exit_edit_form',$perid);
  $render_array['#markup'] .= drupal_render($form);
  $render_array['#markup'] .= '</div>';
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;
}

function company_exit_edit_form($form, &$form_state, $perid){
  $query = "SELECT * FROM " .
           "{company_exit_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $exit_timestamp = '';   
  $exit_type = '';
  $exit_money = '';
  $remark = '';

  foreach ($queryResult as $links ) {
	  $exit_timestamp =  getdate($links->exit_timestamp);
	  $exit_type = $links->exit_type;
	  $exit_money = $links->exit_money;
	  $remark = $links->remark;
  }
  // More coming....
  if ($queryResult == '') {
    $form = NULL;
  }
  else{
   $form['bid'] = array('#type' => 'hidden', '#value' => $perid);

     $form['exit_timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('退出时间'),
	     '#default_value' => array('year' =>  $exit_timestamp['year'], 'month' =>  $exit_timestamp['mon'], 'day' => $exit_timestamp['mday']), 
	 );
	 $form['exit_money'] = array(
	  '#title' => t('退出金额（万元）'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['company_exit_form']['exit_money'])?$_SESSION['company_exit_form']['exit_money']:$exit_money,
	  '#description' => t('例如：250.55'),
	 ); 
	 $form['exit_type'] = array(
	  '#title' => t('退出方式'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['company_exit_form']['exit_type'])?$_SESSION['company_exit_form']['exit_type']:$exit_type,
	 ); 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['company_exit_form']['remark'])?$_SESSION['company_exit_form']['remark']:$remark,
	 );
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	  
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该企业信息'),
	    '#submit' => array('company_exit_edit_form_deleate'),
	  );
  	
  }
  
  return $form;
}

function company_exit_edit_form_submit($form, &$form_state){
	  $values = NULL;
	  $values = $form_state['values'];
      $exit_timestamp = mktime(0, 0, 0,$values['exit_timestamp']['month'], $values['exit_timestamp']['day'], $values['exit_timestamp']['year']);
	   db_update('company_exit_info')
  		->fields(array(
             'exit_timestamp' => $exit_timestamp,
   			 'exit_money' => $values['exit_money'],
   			 'exit_type' => $values['exit_type'],
   			 'remark' => $values['remark'],
  			))
  		->condition('id', $values['bid'])
  		->execute();
	 $form_state['redirect'] = 'company_exit/list/'.$values['bid'];
}

function company_exit_edit_form_deleate($form, &$form_state){
	 $values = NULL;
	 $_SESSION['company_exit_edit_form'] = $form_state['values'];
	 $values = $_SESSION['company_exit_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'company_exit/deleate/'.$values['bid'];
}

function company_exit_deleate_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该资本退出信息将不可恢复！';
  
  drupal_set_title('删除该资本退出信息');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('company_exit_deleate_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function company_exit_deleate_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('company_exit_deleate_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function company_exit_deleate_form_back($form, &$form_state){
	if(empty($_SESSION['company_exit_edit_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'company_exit/fundlist';
	  }else{
		  $values = $_SESSION['company_exit_edit_form'];
		  unset($_SESSION['company_exit_edit_form']);
		  $form_state['redirect'] = 'company_exit/list/'.$values['bid'];
	  }
}

function company_exit_deleate_form_submit($form, &$form_state){
  //简单的重定向到contactus页面
 if(empty($_SESSION['company_exit_edit_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'qiye_tcbg_file/fundlist/';
	  }else{
		  $values = $_SESSION['company_exit_edit_form'];
		  unset($_SESSION['company_exit_edit_form']);
		  db_delete('company_exit_info')
			->condition('id' ,$values['bid'])
			->execute();
		  $query = "SELECT fund_id FROM " .
           "{company_exit_info} where id = ?";
		  $queryResult = db_query($query, array($values['bid']));
		  foreach ($queryResult as $result) {
  			$form_state['redirect'] ='company_exit/fundlist/'.$result->fund_id;
		  }	  
	  }

}

//////////
//基金退出
//////////
function fund_exit_create($fund_id){
	  //我们为这个页面设置标题
	 drupal_set_title('新增基金退出信息');
	 $page_content = '';
	 $page_content = l('返回基金列表','fund_exit/fundlist') . '<br />'. '<br />';
	 $query = "SELECT name FROM " .
           "{guiding_fund_info} where id = ?";
    $queryResult = db_query($query, array($fund_id));
	
    foreach ($queryResult as $result) {
       $page_content .= '当前基金：'.$result->name. '<br />'. '<br />';    
    }

	 $render_array = array(
	   '#markup' => $page_content, 
	 );
	 
	 $form = drupal_get_form('fund_exit_form',$fund_id);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function fund_exit_form($form, &$form_state, $fund_id){
	 $form['bid'] = array('#type' => 'hidden', '#value' => $fund_id);
	 
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['exit_money'] = array(
	  '#title' => t('利润额(万元)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['fund_exit_form']['exit_money'])?$_SESSION['fund_exit_form']['exit_money']:"",
	  '#description' => t('例如：250.55'),
	 );
	 $form['profit_percentage'] = array(
	  '#title' => t('总体收益率'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['fund_exit_form']['profit_percentage'])?$_SESSION['fund_exit_form']['profit_percentage']:"",
	  '#description' => t('例如：16.8'),
	 );
	 $form['irr'] = array(
	  '#title' => t('IRR'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['fund_exit_form']['irr'])?$_SESSION['fund_exit_form']['irr']:"",
	 );
	 $today = getdate();
     $form['exit_timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('退出时间'),
	     '#default_value' => array('year' =>  $today['year'], 'month' =>  $today['mon'], 'day' => $today['mday']), 
	 );
	 $form['exit_type'] = array(
	  '#title' => t('退出方式'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['fund_exit_form']['exit_type'])?$_SESSION['fund_exit_form']['exit_type']:"",
	 ); 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['fund_exit_form']['remark'])?$_SESSION['fund_exit_form']['remark']:"",
	 );
	
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认退出'),
	  );
	  return $form;
}

function fund_exit_form_validate($form, &$form_state){
	  if (drupal_strlen($form_state['values']['exit_money']) > 15) {
	    form_set_error('exit_money', '要求精度小于15 个字符');
	  } 
	  if (!($form_state['values']['exit_money']>=0 || $form_state['values']['exit_money']<0  )) {
	    form_set_error('exit_money', '请输入数字');
	  }  
	   if (drupal_strlen($form_state['values']['profit_percentage']) > 15) {
	    form_set_error('profit_percentage', '要求精度小于15 个字符');
	  } 
	  if (!($form_state['values']['profit_percentage']>=0 || $form_state['values']['profit_percentage']< 0)) {
	    form_set_error('profit_percentage', '请输入数字');
	  }  
	   if (drupal_strlen($form_state['values']['irr']) > 15) {
	    form_set_error('irr', '要求精度小于15 个字符');
	  } 
	  if (!($form_state['values']['irr']>=0 || $form_state['values']['irr']<0)) {
	    form_set_error('irr', '请输入数字');
	  }  
}

function fund_exit_form_submit($form, &$form_state){
	  //把表单的值存放在会话中去，由于这里涉及到了两个不同的表单之间传值。
	 $_SESSION['fund_exit_form'] = $form_state['values'];
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'fund_exit/confirm';
}
 
function fund_exit_confirm_page(){
  //我们为这个页面设置标题
	 drupal_set_title('新增基金退出信息');
	 
	 //这里首先作了判断，如果会话中没有设置contactus_form，返回contactus
	 if(empty($_SESSION['fund_exit_form'])){
	  drupal_goto('fund_exit/fundlist');
	 }	
	 $render_array = array(
	   '#markup' => '', 
	 );
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('fund_exit_confirm_form');
	 $render_array['#markup'] .= drupal_render($form);
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function fund_exit_confirm_form(){
     
     $form['exit_money'] = array(
	  '#title' => t('利润额(万元)'),
	  '#type' => 'item',
	  '#markup' =>isset($_SESSION['fund_exit_form']['exit_money'])?$_SESSION['fund_exit_form']['exit_money']:"",
	 );
	 $form['profit_percentage'] = array(
	  '#title' => t('总体收益率'),
	  '#type' => 'item',
	  '#markup' =>isset($_SESSION['fund_exit_form']['profit_percentage'])?$_SESSION['fund_exit_form']['profit_percentage']:"",
	 );
	 $form['irr'] = array(
	  '#title' => t('IRR值'),
	  '#type' => 'item',
	  '#markup' =>isset($_SESSION['fund_exit_form']['irr'])?$_SESSION['fund_exit_form']['irr']:"",
	 );
	 $exit_timestamp = $_SESSION['fund_exit_form']['exit_timestamp'];
     $form['exit_timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('退出时间'),
	     '#markup' => isset($_SESSION['fund_exit_form']['exit_timestamp'])?$exit_timestamp['year'].'年'.$exit_timestamp['month'].'月'.$exit_timestamp['day'].'日':"", 
	 );
	 $form['exit_type'] = array(
	  '#title' => t('退出方式'),
	  '#type' => 'item',
	  '#markup' =>isset($_SESSION['fund_exit_form']['exit_type'])?$_SESSION['fund_exit_form']['exit_type']:"",
	 ); 
	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'item',
	  '#markup' =>isset($_SESSION['fund_exit_form']['remark'])?$_SESSION['fund_exit_form']['remark']:"",
	 );

	  $form['back'] = array(
	    '#type' => 'submit',
	    '#value' => t('返回'),
	    '#submit' => array('fund_exit_confirm_form_back'),
	  );
	
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交'),
	  );
	  
	  return $form;
}

function fund_exit_confirm_form_back($form, &$form_state){
 $form_state['redirect'] = 'fund_exit/create/'.$_SESSION['fund_exit_form']['bid'];
}

function fund_exit_confirm_form_submit($form, &$form_state){
		/**
	   * 写入数据库
	   */
	  $values = NULL;
	  global  $user;
	  if(empty($_SESSION['fund_exit_form'])){
		  drupal_goto('fund_exit/create/'.$values['bid']);
	  }else{
		  $values = $_SESSION['fund_exit_form'];
		  unset($_SESSION['fund_exit_form']);
	  }
      $exit_timestamp = mktime(0, 0, 0,$values['exit_timestamp']['month'], $values['exit_timestamp']['day'], $values['exit_timestamp']['year']);

	  $last_id = db_insert('fund_exit_info')
  		->fields(array(
  		     'fund_id' =>  $values['bid'],
   			 'exit_timestamp' => $exit_timestamp,  			 
   			 'exit_type' => $values['exit_type'],
   			 'exit_money' => $values['exit_money'],
             'profit_percentage' => $values['profit_percentage'],
   			 'irr' => $values['irr'],
   			 'remark' => $values['remark'],
  			))->execute();
	  if ($last_id!=NULL) {
	  	db_update('guiding_fund_info')
  		->fields(array(
  		     'state' => 8,
  			))
  		->condition('id',$values['bid'])
  		->execute();
		 $form_state['redirect'] = 'fund_exit/list/'.$last_id;
	  } else {	    
	    // 数据写入失败了
	    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
	    
	  }	
}

//传人基金退出id
function fund_exit_exportcsv_perpage($fund_id){
  $filename = '基金退出信息.csv' ;
  drupal_add_http_header('Content-Type', 'text/csv; charset=utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $filename . '"');
  $header = array(
      // iconv('utf-8','gb2312','序号'),
       iconv('utf-8','gb2312','基金名称'),
       iconv('utf-8','gb2312', '利润额（万元）'),
       iconv('utf-8','gb2312','总体收益率'),
       iconv('utf-8','gb2312','irr值'),              
       iconv('utf-8','gb2312','退出时间'),
       iconv('utf-8','gb2312', '退出方式'),
       iconv('utf-8','gb2312', '备注'),
      );
  print implode(',', $header) ."\r\n";
  $query = db_select('fund_exit_info', 'n')
      ->fields ('n', array (
      'id',
      'exit_money',
      'profit_percentage',
      'irr',
      'remark',
      'exit_timestamp',
      'exit_type',
      ))
	  ->condition('id',$fund_id,'=');
  $results = $query
      ->execute();
  foreach ($results as $node) { 
	  $query = "SELECT name FROM " .
           "{guiding_fund_info} where id = ?";
	  $queryResult = db_query($query, array($fund_id));
	  $fund_name = '';
	  foreach ($queryResult as $result) {
	  	$fund_name = $result->name;
	  }
	  $exit_timestamp = str_replace(array(',',",",'，',"，") , " ", format_date($node->exit_timestamp, 'custom', 'Y-m-d'));
     
      $values = array( $fund_name,$node->exit_money, $node->profit_percentage,$node->irr,
      	$exit_timestamp,$exit_type,$remark); 
	  $str = implode(',', $values) ."\r\n";
	  $str = iconv('utf-8','gb2312',$str);
	  print $str;
	  //$serial_num+=1;
    }  
}

function fund_exit_exportcsv_page(){
  $filename = '基金退出信息列表.csv' ;
  drupal_add_http_header('Content-Type', 'text/csv; charset=utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $filename . '"');
  $header = array(
       iconv('utf-8','gb2312','序号'),
       iconv('utf-8','gb2312','基金名称'),
       iconv('utf-8','gb2312', '利润额（万元）'),
       iconv('utf-8','gb2312','总体收益率'),
       iconv('utf-8','gb2312','irr值'),              
       iconv('utf-8','gb2312','退出时间'),
       iconv('utf-8','gb2312', '退出方式'),
       iconv('utf-8','gb2312', '备注'),
      );
  print implode(',', $header) ."\r\n";
  $query = db_select('fund_exit_info', 'n')
      ->fields ('n', array (
       'id',
      'exit_money',
      'profit_percentage',
      'irr',
      'remark',
      'exit_timestamp',
      'exit_type',
      ));
  $results = $query
      ->execute();
  $serial_num = 1;
 
  foreach ($results as $node) {
  	  $query = "SELECT name FROM " .
           "{guiding_fund_info} where id = ?"; 
	  $queryResult = db_query($query, array($node->id));
	  $fund_name = '';
	  foreach ($queryResult as $result) {
		  $fund_name = $result->name;
	  }
      $exit_timestamp= str_replace(array(',',",",'，',"，") , " ", format_date($node->exit_timestamp, 'custom', 'Y-m-d'));
     
      $values = array($serial_num, $fund_name, $node->exit_money, $node->profit_percentage, 
     	 $node->irr, $exit_timestamp, $node->exit_type,$node->remark, ); 
	  $str = implode(',', $values) ."\r\n";
	  $str = iconv('utf-8','gb2312',$str);
	  print $str;
	  $serial_num+=1;
    }

  
}

function fund_exit_fundlist_page() {

  if(!user_access( 'upload fund template file')){
 		global $user;
      $html = '';
      // 如果没有通过尽调审批，则不开放此功能
        $failed = 1;
      $authquery = db_select('nishejijin', 'n')
          ->fields ('n', array (
              'id',
              'state',
          ))
          ->condition('user_id',$user->uid,'=');
      $authresults = $authquery
          ->execute();
      foreach ($authresults as $node) {
          if ($node->state >= 7) {
              $failed = 0;
          }
      }
      if ($failed == 1) {
          drupal_goto('fund_exit/fail');
      }
		$query = "SELECT fund_id FROM {fund_basic_information} WHERE user_id = ?";
		$query_result = db_query($query,array($user->uid));
		$result_values = '';
		$fund_id = "";
		foreach ($query_result as $result_values ) {
			$fund_id = $result_values->fund_id;
		}
		$header1 = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '退出时间', 'field' => 'exit_timestamp'),
      array('data' => '退出方式', 'field' => 'exit_type'),
      array('data' => '利润额(万元)', 'field' => 'exit_money'),
      array('data' => '总体收益率', 'field' => 'profit_percentage'),
      array('data' => 'irr值', 'field' => 'irr'),
      array('data' => '详情', 'field' => 'set'),
      );
  $header2 = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '基金退出设置', 'field' => 'set'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->fields ('n', array (
      'id',
      'name',
      'timestamp',
      ))
	  ->condition('id',$fund_id,'=');
  $results = $query
      ->execute();
  $html =  '';
  $rows1 = array();
  $rows2 = array();
  foreach ($results as $node) {
     $query = "SELECT id, exit_timestamp, exit_type, exit_money, profit_percentage, irr FROM " .
           "{fund_exit_info} where fund_id = ?"; 
	  $queryResult = db_query($query, array($node->id));
	  $exit_id = '';
	  $exit_timestamp = '';
	  $exit_type = '';
	  $exit_money = '';
	  $profit_percentage = '';
	  $irr = '';
	  foreach ($queryResult as $result) {
		  $exit_id = $result->id;
		  $exit_timestamp = $result->exit_timestamp;
		  $exit_type = $result->exit_type;
		  $exit_money = $result->exit_money;
		  $profit_percentage = $result->profit_percentage;
		  $irr = $result->irr;
	  }
	 if($exit_id>0){
	 	$rows1[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/edit/'. $node->id),
	        format_date($node->timestamp, 'custom', 'Y-m-d'),
	        format_date($exit_timestamp, 'custom', 'Y-m-d'),
	        $exit_type,
	        $exit_money,
            $profit_percentage,
            $irr,
	         l('查看', 'fund_exit/list/'. $exit_id),
	      )
      );
  		 
	  }
	  else{
	  	$rows2[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/edit/'. $node->id),
	        format_date($node->timestamp, 'custom', 'Y-m-d'),	        
	         l('编辑', 'fund_exit/create/'. $node->id),
	      )
      );
	  	
	  }
  }
  $html .= '<br><h4><B>已退出基金列表</B></h4><br>';
  $html .= theme('table', 
       	 array(
            'header' => $header1,
            'rows'=>$rows1,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有退出基金记录',//Optional empty text for the table if resultset is empty
     	 )
     	 );
   $html .= theme('pager',
	      array(
	            'tags' => array()
	      )
	      ); 
   $html .= '<br><h4><B>未退出基金列表</B></h4><br>';	  
   $html .= theme('table', 
	      array(
	            'header' => $header2,
	            'rows'=>$rows2,
	            //'caption' => '反馈意见列表',//Optional Caption for the table
	            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
	            'empty' => '没有未退出基金记录',//Optional empty text for the table if resultset is empty
	      )
	      );
   $html .= theme('pager',
	      array(
	            'tags' => array()
	      )
	      ); 
		  
  return ($html); 
  }
  $header1 = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '退出时间', 'field' => 'exit_timestamp'),
      array('data' => '退出方式', 'field' => 'exit_type'),
      array('data' => '利润额(万元)', 'field' => 'exit_money'),
      array('data' => '总体收益率', 'field' => 'profit_percentage'),
      array('data' => 'irr值', 'field' => 'irr'),
      array('data' => '详情', 'field' => 'set'),
      );
  $header2 = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '基金退出设置', 'field' => 'set'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->fields ('n', array (
      'id',
      'name',
      'timestamp',
      ));
  $results = $query
      ->execute();
  $html =  '';
  $rows1 = array();
  $rows2 = array();
  foreach ($results as $node) {
     $query = "SELECT id, exit_timestamp, exit_type, exit_money, profit_percentage, irr FROM " .
           "{fund_exit_info} where fund_id = ?"; 
	  $queryResult = db_query($query, array($node->id));
	  $exit_id = '';
	  $exit_timestamp = '';
	  $exit_type = '';
	  $exit_money = '';
	  $profit_percentage = '';
	  $irr = '';
	  foreach ($queryResult as $result) {
		  $exit_id = $result->id;
		  $exit_timestamp = $result->exit_timestamp;
		  $exit_type = $result->exit_type;
		  $exit_money = $result->exit_money;
		  $profit_percentage = $result->profit_percentage;
		  $irr = $result->irr;
	  }
	 if($exit_id>0){
	 	$rows1[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/edit/'. $node->id),
	        format_date($node->timestamp, 'custom', 'Y-m-d'),
	        format_date($exit_timestamp, 'custom', 'Y-m-d'),
	        $exit_type,
	        $exit_money,
            $profit_percentage,
            $irr,
	         l('查看', 'fund_exit/list/'. $exit_id),
	      )
      );
  		 
	  }
	  else{
	  	$rows2[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/edit/'. $node->id),
	        format_date($node->timestamp, 'custom', 'Y-m-d'),	        
	         l('编辑', 'fund_exit/create/'. $node->id),
	      )
      );
	  	
	  }
  }
  $html .= '<br><h4><B>已退出基金列表</B></h4><br>';
  $html .= theme('table', 
       	 array(
            'header' => $header1,
            'rows'=>$rows1,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有退出基金记录',//Optional empty text for the table if resultset is empty
     	 )
     	 );
   $html .= theme('pager',
	      array(
	            'tags' => array()
	      )
	      ); 
   $html .= '<br><h4><B>未退出基金列表</B></h4><br>';	  
   $html .= theme('table', 
	      array(
	            'header' => $header2,
	            'rows'=>$rows2,
	            //'caption' => '反馈意见列表',//Optional Caption for the table
	            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
	            'empty' => '没有未退出基金记录',//Optional empty text for the table if resultset is empty
	      )
	      );
   $html .= theme('pager',
	      array(
	            'tags' => array()
	      )
	      ); 
		  
  return ($html); 
}

function fund_exit_fail_page() {
    $html = '';
    $html.= '<div>对不起，您申报的基金尚在审批中（或者您没有申报任何基金），暂时无法使用退出管理功能</div>';
    return $html;
}

//传人基金退出id
function fund_exit_per_page($perid) {
 
  // content variable that will be returned for display
  $page_content = '';
  $page_content .= l('返回基金列表','fund_exit/fundlist') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';     
  $page_content .= l('导出','fund_exit/exportcsv/per/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  drupal_set_title('管理该项基金退出信息');
  $options = array(
  'target_id' => 'printable_div',
  'value' => t('Print'),
  'type' => 'link',
  'custom_css' => drupal_get_path('module','my_module').'/css/print.css',
  );

  $page_content .= area_print_form($options). '<br />'. '<br />';
  
  $page_content .= '<div id="printable_div">';
  	 
  $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
  $form = drupal_get_form('fund_exit_edit_form',$perid);
  $render_array['#markup'] .= drupal_render($form);
  $render_array['#markup'] .= '</div>';
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;
}

function fund_exit_edit_form($form, &$form_state, $perid){
  $query = "SELECT * FROM " .
           "{fund_exit_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $exit_timestamp = '';
  $exit_type = '';
  $exit_money = '';
  $profit_percentage = '';
  $irr = '';
  $remark = '';

  foreach ($queryResult as $links ) {
	  $exit_timestamp =  getdate($links->exit_timestamp);
	  $exit_type = $links->exit_type;
	  $exit_money = $links->exit_money;
	  $profit_percentage = $links->profit_percentage ;
	  $irr = $links->irr;
	  $remark = $links->remark;
  }
  // More coming....
  if ($exit_timestamp == '') {
    $form = NULL;
  }
  else{
   $form['bid'] = array('#type' => 'hidden', '#value' => $perid);
   $form['exit_money'] = array(
	  '#title' => t('利润额(万元)'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['fund_exit_form']['exit_money'])?$_SESSION['fund_exit_form']['exit_money']:$exit_money,
	  '#description' => t('例如：250.55'),
	 ); 
	 $form['profit_percentage'] = array(
	  '#title' => t('总体收益率'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['fund_exit_form']['profit_percentage'])?$_SESSION['fund_exit_form']['profit_percentage']:$profit_percentage,
	 ); 
	 $form['irr'] = array(
	  '#title' => t('irr值'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['fund_exit_form']['irr'])?$_SESSION['fund_exit_form']['irr']:$irr,
	 ); 
	 
     $form['exit_timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('退出时间'),
	     '#default_value' => array('year' =>  $exit_timestamp['year'], 'month' =>  $exit_timestamp['mon'], 'day' => $exit_timestamp['mday']), 
	 );
	 
	 $form['exit_type'] = array(
	  '#title' => t('退出方式'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['fund_exit_form']['exit_type'])?$_SESSION['fund_exit_form']['exit_type']:$exit_type,
	 ); 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['fund_exit_form']['remark'])?$_SESSION['fund_exit_form']['remark']:$remark,
	 );
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	  
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该基金退出信息'),
	    '#submit' => array('fund_exit_edit_form_deleate'),
	  );
  	
  }
  
  return $form;
}

function fund_exit_edit_form_validate($form, &$form_state){
	  if (drupal_strlen($form_state['values']['exit_money']) > 15) {
	    form_set_error('exit_money', '要求精度小于15 个字符');
	  } 
	  if (!($form_state['values']['exit_money']>=0 || $form_state['values']['exit_money']<0  )) {
	    form_set_error('exit_money', '请输入数字');
	  }  
	   if (drupal_strlen($form_state['values']['profit_percentage']) > 15) {
	    form_set_error('profit_percentage', '要求精度小于15 个字符');
	  } 
	  if (!($form_state['values']['profit_percentage']>=0 || $form_state['values']['profit_percentage']< 0)) {
	    form_set_error('profit_percentage', '请输入数字');
	  }  
	   if (drupal_strlen($form_state['values']['irr']) > 15) {
	    form_set_error('irr', '要求精度小于15 个字符');
	  } 
	  if (!($form_state['values']['irr']>=0 || $form_state['values']['irr']<0)) {
	    form_set_error('irr', '请输入数字');
	  }  
}

function fund_exit_edit_form_submit($form, &$form_state){
	  $values = NULL;
	  $values = $form_state['values'];
      $exit_timestamp = mktime(0, 0, 0,$values['exit_timestamp']['month'], $values['exit_timestamp']['day'], $values['exit_timestamp']['year']);
	   db_update('fund_exit_info')
  		->fields(array(
             'exit_timestamp' => $exit_timestamp,
   			 'exit_money' => $values['exit_money'],
   			 'profit_percentage' => $values['profit_percentage'],
   			 'irr' => $values['irr'],
   			 'exit_type' => $values['exit_type'],
   			 'remark' => $values['remark'],
  			))
  		->condition('id', $values['bid'])
  		->execute();
	 $form_state['redirect'] = 'fund_exit/list/'.$values['bid'];
}

function fund_exit_edit_form_deleate($form, &$form_state){
	 $values = NULL;
	 $_SESSION['fund_exit_edit_form'] = $form_state['values'];
	 $values = $_SESSION['fund_exit_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'fund_exit/deleate/'.$values['bid'];
}

function fund_exit_deleate_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该基金退出信息将不可恢复！';
  
  drupal_set_title('删除该基金退出信息');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('fund_exit_deleate_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function fund_exit_deleate_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('fund_exit_deleate_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function fund_exit_deleate_form_back($form, &$form_state){
	if(empty($_SESSION['fund_exit_edit_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fund_exit/fundlist';
	  }else{
		  $values = $_SESSION['fund_exit_edit_form'];
		  unset($_SESSION['fund_exit_edit_form']);
		  $form_state['redirect'] = 'fund_exit/list/'.$values['bid'];
	  }
}

function fund_exit_deleate_form_submit($form, &$form_state){
  //简单的重定向到contactus页面
 if(!empty($_SESSION['fund_exit_edit_form'])){
		  $values = $_SESSION['fund_exit_edit_form'];
		  unset($_SESSION['fund_exit_edit_form']);
		  db_delete('fund_exit_info')
			->condition('id' ,$values['bid'])
			->execute();
		  $query = "SELECT fund_id FROM " .
           "{fund_exit_info} where id = ?";
		  $queryResult = db_query($query, array($values['bid']));
 }
  $form_state['redirect'] = 'fund_exit/fundlist/';
}
